【发布时间】:2019-09-25 11:16:34
【问题描述】:
我正在尝试连接到在我的笔记本电脑上运行的 node.js 服务器,我编写了一个颤振应用程序,当通过同一台笔记本电脑上的模拟器运行时,它可以很好地连接到服务器,但是当我构建一个 apk 并安装我的android设备上的应用程序,它没有连接到服务器。笔记本电脑连接到手机的热点。此外,当我通过应用程序“REST Api Client”发送相同的请求时,它会连接到服务器并获得很好的响应。我在这里缺少什么或者我可以尝试做什么?
Future<String> _makeGetRequest(name, pass) async {
Response response1 =
await post(_localhost(), headers: {"username": name, "password": pass});
print(response1.body);
return response1.body;
}
String _localhost() {
if (Platform.isAndroid)
return 'http://192.168.43.236:3000/';
else
return 'http://localhost:3000';
}
Node.js 服务器代码
import express = require('express');
import bodyParser = require('body-parser');
const app = express();
const hostname: string = '192.168.43.236';
const port = 3000;
const username = 'username';
const pass = '123456';
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', (req, res) => {
const postBody = req.headers;
console.log(postBody.username);
console.log(postBody.password);
if (req.headers.username == username && req.headers.password == pass)
res.status(200).send('Success');
else if (req.headers.username != username) {
res.status(404).send('User not found');
}
else if (req.headers.username == username && req.headers.password != pass)
res.status(401).send('Incorrect password');
else
res.status(500).send('Internal Server Error');
});
app.listen(port,hostname, () => {
console.info(`Server running at http://${hostname}:${port}/`);
});
【问题讨论】: