我在使用 Flutter 模拟器连接到本地服务器时遇到问题

问题描述 投票:0回答:1

我正在使用 Flutter 开发 Instagram 克隆应用程序。因此,我用 Node.js 编写了一个简单的 API 工具,用于数据库(Postgre)管理。这是代码;

const express = require('express');
const { Client } = require('pg');

const server = express();
const client = new Client({
    user: 'postgres',
    host: '127.0.0.1',
    database: 'instagram',
    password: 'postgre',
    port: 5432,
});

client.connect(function (err) {
    if (err) {
        console.error(err);
        return;
    }
    console.log("Connected!");
});

const bodyParser = require('body-parser');

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));


server.post('/users', async (req, res) => {
    console.log('Request received:', req.body);
    try {
        const { username, password, email, fullname } = req.body;
        await client.query("INSERT INTO users VALUES ('dssa', 'dssa', 'dssa', 'dssa')");
        res.status(200).send('User created successfully');
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal server error');
    }
});


server.get('/users', async (req, res) => {
    try {
        const result = await client.query("SELECT * FROM users");
        res.send(result.rows);

    } catch (error) {
        console.error(error);
        res.status(500).send('Internal server error');
    }
});


server.listen(5433, () => {
    console.log('http://localhost:5433 is listening... :)');
});

Node.js 没有问题。我对此进行了测试,因为它是在底座连接的。但我在 Flutter 方面遇到了问题。这是代码;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const App());
}

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  Future<void> getUser() async {
    try {
      final url = Uri.parse(
        'https://127.0.0.1:5433/users',
      );
      final response = await http.get(url);

      print(response);
      if (response.statusCode == 200) {
        print('User created successfully');
      } else {
        print('Error: ${response.statusCode}');
      }
    } catch (e) {
      print('Exception occurred: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            const SizedBox(height: 25),
            ElevatedButton(
              onPressed: () async {
                await getUser();
              },
              child: const Text('Get Users'),
            ),
          ],
        ),
      ),
    );
  }
}

当我单击

Get Users
按钮时,出现以下错误;

Exception occurred: ClientException with SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 51908, uri=https://127.0.0.1:5433/users

我该如何解决这个问题?预先感谢。

模拟器代理设置;

flutter dart
1个回答
0
投票

在您的服务器中,

server.listen(...)
,将主机设置为 0.0.0.0。

server.listen(5433, 0.0.0.0, () => {
    console.log('http://localhost:5433 is listening... :)');
});
© www.soinside.com 2019 - 2024. All rights reserved.