简体   繁体   中英

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 It work successfully(I got the req.body). backend is in node js and Front end is in React js. Any help will be appreciated.

节点后端日志 浏览器控制台日志 浏览器中的网络控制台 浏览器中的网络控制台


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

Is this use node-fetch ? So I think you need to add JSON.stringify() to body.

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

Link refers Node Fetch - post with json . I hope it works.

UPDATE If your backend is using ExpressJs make sure you added.

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());

You have to convert you body data to JSON with JSON.stringify .

And also make sure the cors enabled on the backend side.

The issue is with mode: 'no-cors' , Please remove this. AS the application/json is not allowed in no-cors mode.

Note that mode: "no-cors" only allows a limited set of headers in the request:

  1. Accept
  2. Accept-Language
  3. Content-Language Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Try this.

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

}

Also you will needed to bind the function submitHandler at the constructor, to access to ' this '

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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