React native 如何修复使用react native和express js调用localhost api时出现的[Error:Network Error]
我目前正在学习服务器端的React native和Express JS。所以现在我练习从expressjs调用api来响应本机,并使用axios来调用http请求。我的问题在我的cmd中,它显示[错误:网络错误]。更具体地说,我将向你们展示我的示例工作server.js和组件,以及我的cmd上的示例屏幕截图错误 [错误:网络错误] 服务器JS:React native 如何修复使用react native和express js调用localhost api时出现的[Error:Network Error],react-native,express,React Native,Express,我目前正在学习服务器端的React native和Express JS。所以现在我练习从expressjs调用api来响应本机,并使用axios来调用http请求。我的问题在我的cmd中,它显示[错误:网络错误]。更具体地说,我将向你们展示我的示例工作server.js和组件,以及我的cmd上的示例屏幕截图错误 [错误:网络错误] 服务器JS: const express = require('express'); var cors = require('cors') const bodyPar
const express = require('express');
var cors = require('cors')
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : '192.168.61.1',
user : 'root',
password : '',
database : 'sample_db'
});
if(connection) {
console.log(connection);
}
// Starting our app.
const app = express();
var cors = require('cors');
app.use(cors());
// Creating a GET route that returns data from the 'mobile' table.
app.get('/api/readings', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'mobile' table).
connection.query('SELECT * FROM tbl_mobile', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// get the specific meter
app.get('/api/readings/:id', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'mobile' table).
connection.query('SELECT * FROM tbl_mobile WHERE id = ?',req.params.id, function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('http://192.168.61.1/api/readings');
});
Axios:
axios.get('http://192.168.61.1:3000/api/readings')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
答复:
如果您运行的是android,则需要配置明文http流量。IP地址192.168.61.1似乎是网关IP地址。请检查您使用的机器IP地址是否正确。