javascript - POST 请求错误 - Express 服务器 - React Native 网络请求失败
问题描述
我正在尝试向我的快速服务器创建一个 POST 请求,但是我收到网络请求失败错误。我已经浏览了有关此主题的所有类似帖子,但尚未能够解决此问题。
到目前为止我做了什么:
- 我已根据各种 Stack Overflow 帖子修改了服务器中的 POST 路由,但已还原代码以使其保持简单。
- 我已根据各种 Stack Overflow 帖子修改了 React 应用程序中的 POST 请求,但已恢复代码以使其保持简单。
- 我也尝试将 Axios 用于 POST/GET 请求,但遇到了同样的错误。
- 使用邮递员测试服务器(
http://123.456.789.10:3000/login
) - 使用 JSON 正文创建 POST 请求: - 重写了前端方法(2020 年 8 月 1 日)并得到未经处理的 promise 拒绝错误
{
"email": "email@email.com",
"password": "password"
}
并收到回复:
{
"message": "Successful login!"
}
我已经包含了快速服务器和反应应用程序的代码。
服务器:
var express = require('express');
var router = express.Router();
var users = [
{
email: 'email@email.com', password: 'password'
}
]
router.get('/', function(req, res, next) {
res.send('Welcome to the backend server!');
});
router.post('/login', function(req, res){
let result = users.find(user => user.email == req.body.email);
if(result) {
if(result.password == req.body.password) {
res.status(200).send( {
message: "Successful login!"
})
} else {
res.status(200).send( {
message: "Password Incorrect!"
})
}
} else {
res.status(200).send( {
message: "User not found!"
})
}
});
module.exports = router;
反应原生前端:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, Button } from 'react-native';
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
}
}
login = () => {
const data = { email: 'email@email.com', password: 'password' };
return fetch('http://123.456.789.10:3000/login', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
render (){
return (
<View style={styles.container}>
<Button
title="Press me"
onPress={this.login}
/>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
控制台输出:
Error:, [TypeError: Network request failed]
* [native code]:null in __expoConsoleLog
- node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:169:6 in registerError
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:84:8 in errorImpl
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:63:4 in console.error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:4 in error
* App.js:27:11 in fetch.then.then._catch$argument_0
- node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:183:16 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:446:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:396:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:144:6 in __guard$argument_0- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:4 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
更新:将前端重写为后出现新错误
export default class App extends React.Component {
constructor(){
super();
this.state = {
text: ''
};
}
render () {
return (
<View style={styles.container}>
<Button
title="Press me"
onPress={this._postData}
/>
<Text>{this.state.text}</Text>
<StatusBar style="auto" />
</View>
);
}
_postData = async () => {
try {
let formData = new FormData();
formData.append('email', 'email@email.com');
formData.append('password', 'password');
fetch('http://123.456.789.10:3000/login', {
method: 'POST',
body: formData
}).then((response) => response.json())
.then((responseJson) => {
this.setState({text: JSON.stringify(responseJson)})
})
} catch (e){
console.log(e);
}
}
}
新错误:
[Unhandled promise rejection: TypeError: Network request failed]
- node_modules\whatwg-fetch\dist\fetch.umd.js:511:17 in setTimeout$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:135:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:387:16 in callTimers
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
解决方案
推荐阅读
- covariance - 与 r 中的协变量配对的 Wilcoxon 检验
- azure - 我正在尝试将天蓝色地图渲染到我的应用程序中,但瓷砖似乎在重复。如何限制图块,使每个部分只渲染一次?
- android - React Native Image 需要在角落显示图像
- reactjs - 故事书:相同的文件,但用 npm 或 yarn 呈现不同,为什么?
- python - 我们如何让用户等待一秒钟,请在 Django 中等待消息,就像我们在 PHP 中显示的带有刷新标签一样?
- web-scraping - 使用美丽的汤刮位置
- python - 如何在 python 中以树结构打印 Trie?
- javascript - React JS - 在开发和构建之前获取并将道具传递给应用程序
- rust - 引用 Rust 中相同结构内的字段
- swiftui - 如何获得 SwiftUI 手势的视图?