使用ReactJS发布表单时出现网络错误

时间:2018-07-03 10:39:37

标签: javascript mysql node.js reactjs axios

我是新开发人员 ReactJS ,我开发了一个注册表单,其中包含前端的 ReactJS ,后端的 NodeJS MySQL

我想提交注册表,当我在Postman上测试后端时,它运行良好并在数据库中插入一个日期,例如:{ "code": 200, "success": "user registered sucessfully" }

我的代码如下:

import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
import Login from './Login';

class Register extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            email: '',
            password: ''
        }
    }
    componentWillReceiveProps(nextProps) {
        console.log("nextProps", nextProps);
    }
    handleClick(event, role) {
        var apiBaseUrl = "http://localhost:4000/api";


        if (this.state.username.length > 0 && this.state.email.length > 0 && this.state.password.length > 8) {
            var payload = {
                "username": this.state.username,

                "email": this.state.email,
                "password": this.state.password
            }
            axios.post(apiBaseUrl + '/register', payload)
                .then(function(response) {
                    console.log(response);
                    if (response.data.code === 200) {
                        console.log("registration successfull");
                    }
                    else {
                        console.log("some error ocurred", response.data.code);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                });
        }
        else {
            alert("Input field value is missing");
        }

    }
    render() {

        return (
            <div>
        <MuiThemeProvider>
          <div>
          <AppBar
             title="Register"
           />
           <TextField
             hintText="Enter votre username"
             floatingLabelText="Username"
             onChange = {(event,newValue) => this.setState({username:newValue})}
             />
           <br/>

           <TextField
           type = "email"
             hintText="Email"
             floatingLabelText="Email"
             onChange = {(event,newValue) => this.setState({email:newValue})}
             />
           <br/>
           <TextField
             type = "password"
             hintText="Enter your Password"
             floatingLabelText="Password"
             onChange = {(event,newValue) => this.setState({password:newValue})}
             />
           <br/>
           <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
          </div>
         </MuiThemeProvider>
      </div>
        );
    }
}

const style = {
    margin: 15,
};

export default Register;

我的package.json是:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.8.5"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "material-ui": "^0.20.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-dropzone": "^3.10.0",
    "react-file-tree": "0.0.8",
    "react-router-dom": "^4.0.0",

  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:4000/"
}

运行前端时,我得到:

xhr.js:175 OPTIONS http://localhost:4000/api//register 0 ()
dispatchXhrRequest @ xhr.js:175
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:57
Axios.(anonymous function) @ Axios.js:77
wrap @ bind.js:9
handleClick @ Register.js:33
onClick @ Register.js:93
EnhancedButton._this.handleClick @ EnhancedButton.js:146
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421

Register.js:53 Error: Network Error
    at createError (createError.js:15)
    at XMLHttpRequest.handleError (xhr.js:87)

请问如何解决?

3 个答案:

答案 0 :(得分:1)

如果您在其他端口中运行前端,则可能是CORS的原因。后端不允许来自不同服务器或端口上运行的前端的请求。为了避免这种情况,您可以将此代码添加到前端:(最好将其包含在app.js文件中,以确保它可以在所有脚本中使用)

axios.defaults.withCredentials = true;

此外,您需要将以下代码添加到您的NodeJS后端:(最好包含在server.js中)(我想您使用快速框架)

var app = express();
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:YOUR_FRONT_END_PORT');
  res.setHeader('Access-Control-Allow-Credentials', true);
  res.setHeader('Access-Control-Allow-Methods', ['PATCH', 'POST', 'GET', 'DELETE', 'PUT']);
  res.setHeader('Access-Control-Allow-Headers', ['Content-Type']);
  res.setHeader('Access-Control-Expose-Headers', ['Content-Type']);
  next();
});

如果使用任何自定义中间件,则可能还需要以下代码。在您的中间件中添加:

if (req.method === "OPTIONS") {
  return next();
}

但是,如果您不知道如何处理这些例外情况,请将来考虑使用类似NGINX的Web服务器。

答案 1 :(得分:1)

如前所述-如果您的后端位于其他端口或URL上,请记住打开CORS:

    public static void RotateElement(FrameworkElement e)
    {
        RotateTransform rot = new RotateTransform();
        rot.Angle = 180;
        e.RenderTransformOrigin = new Windows.Foundation.Point(.5, .5);
        e.RenderTransform = rot;
    }

还请检查您希望在服务器端获得什么内容-默认情况下,axios.post(apiBaseUrl + '/register', payload, { withCredentials: true }) 将以JSON格式发送数据(将axios.post标头设置为Content-Type)假设它是application/json,然后相应地设置application/x-www-form-urlencoded标头。

Content-Type

答案 2 :(得分:0)

不确定,但是我猜您定义apiBaseUrl的方式不正确。请看看。