POST请求错误-Express Server-反应本机网络请求失败

时间:2020-08-01 07:32:33

标签: javascript react-native express axios expo

我正在尝试向快递服务器创建POST请求,但是出现网络请求失败错误。我已经阅读了有关该主题的所有类似文章,但仍无法解决此问题。

到目前为止我所做的:

  • 我已根据各种Stack Overflow帖子修改了服务器中的POST路由,但恢复了代码以使其更加简单。
  • 我已基于各种Stack Overflow帖子在React应用程序中修改了POST请求,但已还原了代码以使其更加简单。
  • 我还尝试过将Axios用于POST / GET请求,并且遇到相同的错误。
  • 使用邮递员测试服务器(http://123.456.789.10:3000/login)-使用JSON正文创建POST请求:
  • 重写前端方法(8/1/20)并得到无用的承诺拒绝错误
{
    "email": "email@email.com",
    "password": "password"
}

并收到答复:

{
    "message": "Successful login!"
}

我已经包括了快递服务器和react app的代码。

服务器:

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

0 个答案:

没有答案