Sharad kumar
Sharad kumar

Reputation: 207

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.

Node Backend log Browser console log Network console in browser Network console  in browser


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

Upvotes: 4

Views: 9931

Answers (3)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

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

}

Upvotes: 2

ThangLe
ThangLe

Reputation: 970

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

Upvotes: 8

Lucas Matos
Lucas Matos

Reputation: 2908

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

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

Upvotes: 0

Related Questions