繁体   English   中英

Req.body 未定义,而通过 Fetch Api 发布请求

[英]Req.body is Undefined while Post request through Fetch Api

When I try to call the POST Api through fetch method by passing the parameter in body then I got req.body undefined on backend side(Node js side).Also when I call the Same POST api through Postman by passing the parameter in body then它成功运行(我得到了 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

这是使用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 与 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.stringify 将您的身体数据转换为JSON.stringify

并确保在后端启用cors

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

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

  1. 接受
  2. 接受语言
  3. Content-Language Content-Type,值为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain

尝试这个。

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)
    }

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM