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

y0u0uwnf  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(386)

我是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)

请问我怎么修?

z9gpfhce

z9gpfhce1#

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

axios.defaults.withCredentials = true;

另外,您还需要向nodejs后端添加以下代码:(最好包含在server.js中)(我假设您使用的是expressframework)

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服务器。

ppcbkaq5

ppcbkaq52#

不确定,但我想您定义apibaseurl的方式不正确。请看一下。

vtwuwzda

vtwuwzda3#

如前所述-如果您的后端位于不同的端口或url上,请记住启用cors:

axios.post(apiBaseUrl + '/register', payload, { withCredentials: true })

另外,请检查您在服务器端期望的内容-默认情况下 axios.post 将以json格式发送数据(使用 Content-Type 标题设置为 application/json ),如果你期待的话 application/x-www-form-urlencoded 然后设置 Content-Type 相应的标题。

axios.post(apiBaseUrl + '/register', payload, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded'
})

相关问题