【问题标题】:Req.body is Undefined while Post request through Fetch ApiReq.body 在通过 Fetch Api 发布请求时未定义
【发布时间】:2020-08-03 16:03:48
【问题描述】:

当我尝试通过在 body 中传递参数来通过 fetch 方法调用 POST Api 时,我在后端(Node js 端)得到 req.body undefined。此外,当我通过 Postman 通过传递参数调用相同的 POST api 时在正文中然后它成功工作(我得到了req.body)。后端在 node js 中,前端在 React js 中。任何帮助将不胜感激。


import React, { Component } from 'react'
import '../Css/Login.css'

export class Login extends Component {

    constructor(props) {
        super(props)

        this.state = {
            name: "",
            password: ""
        }

        this.onChange = this.onChange.bind(this);
    }

    submitHandler = (e) => {
        e.preventDefault();
        console.log(this.state);
        try {

            let result = fetch('http://localhost:4000/users/login', {
                method: 'POST',
                mode: 'no-cors',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'

                },
                body: { name: this.state.name, password: this.state.password }
            })

            result.then((sucess) => { console.log(sucess) })
        } catch (error) {
            console.log(error)

        }



    }

    onChange(e) {
        this.setState({ [e.target.name]: e.target.value })

    }
    render() {
        return (
            <div>
                <div className="LoginPage">
                    <div class="container Login_div">
                        <div className="Admin_panel"><h2>Admin Panel</h2></div>

                        <form onSubmit={this.submitHandler}>
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="text" name="name" class="form-control" placeholder="Enter email" onChange={this.onChange} />
                            </div>
                            <div class="form-group">
                                <label for="pwd">Password:</label>
                                <input type="password" name="password" class="form-control" placeholder="Enter password" onChange={this.onChange} />
                            </div>

                            <button type="submit" class="btn btn-login">Submit</button>
                        </form>
                    </div>

                </div>
            </div>
        )
    }
}

export default Login

【问题讨论】:

  • 你安装body-parser了吗?
  • 是的,我安装了 body parser.but 得到同样的错误。

标签: javascript node.js reactjs mongodb express


【解决方案1】:

这是使用node-fetch吗?所以我认为你需要在正文中添加JSON.stringify()

try {

    let result = fetch('http://localhost:4000/users/login', {
        method: 'POST',
        mode:'no-cors',
        headers: {
            'Content-Type':'application/json',
            'Accept':'application/json'
        },
        body: JSON.stringify({ name: this.state.name, password: this.state.password })
    });

    result.then((success) => { console.log(success) });
} catch (error) {
    console.log(error);
}

链接指向Node Fetch - post with json。我希望它有效。

更新 如果您的后端使用 ExpressJs,请确保您已添加。

const app = express();

// push them above the router middleware!

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// parse application/json
app.use(express.json());

【讨论】:

  • 我使用了 JSON.stringfy 但仍然出现同样的错误。
  • @Sharadkumar 我更新了我的答案。
  • 我已经用过这个urlencoded了。我附上了错误的截图。请在上面找到附件。
  • 是的,我看到你的错误,但你能否提供请求数据的详细信息,也许400 bad request 来自你向服务器请求数据。
【解决方案2】:

您必须使用 JSON.stringify 将您的身体数据转换为 JSON。

还要确保在后端启用cors

问题在于 mode: 'no-cors' ,请删除它。因为application/jsonno-cors 模式下是不允许的。

注意 mode: "no-cors" 只允许请求中的一组有限的标头:

  1. 接受
  2. 接受语言
  3. Content-Language Content-Type 的值为 application/x-www-form-urlencoded, multipart/form-data, 或 文本/纯文本

试试这个。

submitHandler = (e) => {
    e.preventDefault();
    console.log(this.state);
    try {
        let result = fetch('http://localhost:4000/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ name: this.state.name, password: this.state.password })
        })
        result.then((sucess) => { console.log(sucess) })
    } catch (error) {
        console.log(error)
    }

}

【讨论】:

  • 我使用了 JSON.stringfy 但仍然出现同样的错误。
  • 您是否在后端启用了 cors。我觉得这个问题与cors有关。
  • 您能否检查开发控制台并检查网络选项卡并查看正在发送到后端的内容。
  • 我附上了错误截图,请在上面找到附件
  • 如果我删除“no-cors”,则会收到错误“请求的资源上不存在“Access-Control-Allow-Origin”标头”错误。
【解决方案3】:

您还需要在构造函数中绑定函数 submitHandler 以访问 'this'

 this.submitHandler =this.submitHandler .bind(this);

【讨论】:

  • submitHandler函数是箭头函数,我们不需要绑定箭头函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多