【问题标题】:400 BAD REQUEST when POST using Axios in React with Nodejs/Express400 BAD REQUEST POST 使用 Axios 在 React 和 Nodejs/Express 中
【发布时间】:2020-03-23 19:21:48
【问题描述】:

我使用 Axios 和 React 来使用 POST 方法到我的 Nodejs 服务器。我第一次尝试它时给了我一个关于 CORS 政策的错误。我已经向它添加了标题,但它仍然给了我 400 的状态代码,提到了这一点:

xhr.js:166 POST http://localhost:3000/api/user/register 400 (Bad Request)
dispatchXhrRequest  @   xhr.js:166
xhrAdapter  @   xhr.js:16
dispatchRequest @   dispatchRequest.js:49
Promise.then (async)        
request @   Axios.js:56
wrap    @   bind.js:11
handleFormSubmit    @   Register.js:21
onClick @   Register.js:69
callCallback    @   react-dom.development.js:363
invokeGuardedCallbackDev    @   react-dom.development.js:412
invokeGuardedCallback   @   react-dom.development.js:465
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:480
executeDispatch @   react-dom.development.js:613
executeDispatchesInOrder    @   react-dom.development.js:638
executeDispatchesAndRelease @   react-dom.development.js:743
executeDispatchesAndReleaseTopLevel @   react-dom.development.js:752
forEachAccumulated  @   react-dom.development.js:724
runEventsInBatch    @   react-dom.development.js:769
runExtractedPluginEventsInBatch @   react-dom.development.js:915
handleTopLevel  @   react-dom.development.js:5866
batchedEventUpdates$1   @   react-dom.development.js:24314
batchedEventUpdates @   react-dom.development.js:1460
dispatchEventForPluginEventSystem   @   react-dom.development.js:5966
attemptToDispatchEvent  @   react-dom.development.js:6083
dispatchEvent   @   react-dom.development.js:5986
unstable_runWithPriority    @   scheduler.development.js:818
runWithPriority$2   @   react-dom.development.js:12259
discreteUpdates$1   @   react-dom.development.js:24331
discreteUpdates @   react-dom.development.js:1485
dispatchDiscreteEvent   @   react-dom.development.js:5949





Error: Request failed with status code 400
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)


我使用 JWT 进行我在 Nodejs 中编写的身份验证 - 在端口 5000 上运行
React - 在端口 3000 上运行
我还有一些用 PHP 编写的其他功能 - 在端口 8000 上运行

在这里,当我将 React Axios 与 PHP 一起使用时,它在满足 CORS 策略后运行良好。但是当我对 Nodejs 这样做时,我得到了这个错误。当我尝试使用 POSTMAN 时,Nodejs Auth 代码工作正常。

这是我在 3000 端口上运行的 React 代码

import React, { Component } from 'react'
import axios from 'axios'

class Register extends Component {
    constructor(props) {
        super(props)
        this.state = {
            name: "",
            email: "",
            password: "",
        }

    }

    handleFormSubmit(e) {
        e.preventDefault();


        const registerData = JSON.stringify(this.state);

        axios({
            method: 'POST',
            url: 'http://localhost:5000/api/user/register',
            headers: {
                'Content-Type': 'application/json',
                    },
            data: registerData,
        })
            .then(result => {
                console.log(registerData)
            })
            .catch(error => console.log(error))
    }
    render() {
        return (
            <div>
                Register
                <br/>
                <form action="#">
                    <label>Full Name</label><br/>
                    <input
                        type='text'
                        id='name'
                        name='name'
                        value={this.props.name}
                        onChange={e => this.setState({ name: e.target.value })} />
                    <br />

                    <label>Email</label><br />
                    <input
                        type='text'
                        id='email'
                        name='email'
                        value={this.props.email}
                        onChange={e => this.setState({ email: e.target.value })} />
                    <br />

                    <label>Password</label><br />
                    <input
                        type='password'
                        id='password'
                        name='password'
                        value={this.props.password}
                        onChange={e => this.setState({ password: e.target.value })} />
                    <br />

                    <input
                        type='submit'
                        onClick={e => this.handleFormSubmit(e)} />
                    <br />
                </form>
            </div>
        )
    }
}

export default Register

这是我在 React 上的 package.json:

{
  "name": "dontbuy",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "react": "^16.10.0",
    "react-dom": "^16.10.0",
    "react-native": "^0.61.1",
    "react-native-web": "^0.11.7",
    "react-router-dom": "^5.1.1",
    "react-scripts": "3.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"
}

这是我在端口 5000 上运行的 Nodejs 代码:(我所有的路由都有前缀 api/user/* )

const router = require('express').Router();
const User = require('../model/User');
const bcrypt = require('bcryptjs');
const { registerValidation, loginValidation } = require('../validation')
const jwt = require('jsonwebtoken');

//API response
router.post('/register' , async (req, res) => {


    //validating the response
    const { error } = registerValidation(req.body);
    if(error){
        return res.status(400).send(error);
    }

    //Check the user is already in the db
    const emailExists = await User.findOne({email: req.body.email});
    if(emailExists){
        return res.status(400).json({"message" : "Email already exists"});
    }

    //Hashing the password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    //Creating a new user
        const user = new User({
            name: req.body.name,
            email: req.body.email,
            password: hashedPassword,
        })
        try {
            const savedUser = await user.save();
            res.send({ user: user._id });
        } catch (err) {
            res.status(400).send(err);
        }  
})


//Login

router.post('/login', async (req, res) => {
    //validation
    const { error } =loginValidation(req.body);
    if(error){
        return res.status(400).send(error.details[0].message);
    }
    //check if the email is already exists
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
        return res.status(400).json({"message": "Email or password is incorrect"});
    }
    const validPassword = await bcrypt.compare(req.body.password, user.password);
    //check if password is correct
    if(!validPassword) {
        return res.status(400).json({"message" :"Password is incorrect"});
    }
    //create and assign a token
    const token = jwt.sign({_id: user._id}, 'secretKey');
    res.header('auth-token', token).send(token);

    res.send('Logged in')
})


module.exports = router;

【问题讨论】:

  • 不要JSON.stringify有效载荷。 Axios 将再次执行此操作,导致一个长字符串
  • 是的,谢谢@apokryfos。但它仍然给我同样的错误。 ://

标签: javascript node.js reactjs axios


【解决方案1】:

回复晚了。这是一些验证错误,我的 React - 前端验证允许将 API 请求发送到我的 Node.js 后端,但验证通过 400 状态码停止了请求。很遗憾,我很长一段时间都没有注意到这个生硬的错误。感谢您花时间回复。

【讨论】:

    【解决方案2】:

    您的服务器在 5000 上运行,您正在从 3000 调用 api。更改 url 中的端口号如下

    axios({
                method: 'POST',
                url: 'http://localhost:5000/api/user/register',
                headers: {
                    'Content-Type': 'application/json',
                        },
                data: registerData,
            })
    

    【讨论】:

    • @Sarath Dev 如果您有解决方案,请投票并接受答案
    • 是的,这是一个错字。但我仍然得到同样的错误。 PS:我现在已经编辑了帖子。
    • 为什么要使用JSON.stringify 状态直接指定为data: this.state
    • 是的。我尝试了所有的可能性。所以我使用了 JSON.stringify。但即使我把它改回 this.state ,我也会得到同样的错误。在过去的两天里,我一直坚持这一点。仍然没有得到解决方案:(
    【解决方案3】:

    尝试改变 return res.status(400).json({"message" : "Email already exists"})到这个 res.status(400).send({"message" : "Email already exists"}))

    localhost:3000localhost:5000

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 2020-06-26
      • 2020-04-17
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多