php - Flutter - 尝试从 localhost api 获取数据 - 获取主机错误
问题描述
我是新来的。为测试应用程序建立一个测试api。试图从中获取数据并得到错误:
SocketException(SocketException:操作系统错误:连接被拒绝,errno = 111,地址 = site.local,端口 = 49882)
操作系统 Ubuntu 20.04、Nginx、php-fpm.7.3、
尝试使用 / 和不使用端口相同的结果。我该如何解决我的问题?
import 'dart:async';
import 'dart:convert';
import 'posts.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Posts> fetchPosts() async {
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response =
await http.get('http://site.local:80/api/posts', headers: requestHeaders);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Posts.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load posts');
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Posts> futurePosts;
@override
void initState() {
super.initState();
futurePosts = fetchPosts();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Posts>(
future: futurePosts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
帖子模型
class Posts {
final int id;
final String title;
final String description;
final String createdAt;
final String updatedAt;
Posts({this.id, this.title, this.description, this.createdAt, this.updatedAt});
factory Posts.fromJson(Map<String, dynamic> json) {
return Posts(
id: json['id'],
title: json['title'],
description: json['description'],
createdAt: json['created_at'],
updatedAt: json['updated_at']
);
}
}
当我使用请求进行Postman
请求时,它会返回此JSON
响应:
[
{
"id": 21,
"title": "Test 1",
"description": "Desc test 1",
"created_at": "2019-12-28 21:20:00",
"updated_at": "2019-12-28 21:20:00"
},
{
"id": 22,
"title": "Test 2",
"description": "Desc test 2",
"created_at": "2019-12-28 21:20:00",
"updated_at": "2019-12-28 21:20:00"
}
]