TMLS_123
TMLS_123

Reputation: 181

When I make post request form react the I recieve an empty body in the back end. I do not understand why

I have been trying to make a post request using react to a node.js backend. Making post requests with postman works fine and the get requests work fine as well. Here is my react code. No matter what I try the req.body recieved is always empty in the node backend.

import axios from "axios";

class PostForm extends Component {
    constructor(props){
        super(props)

        this.state = {
            userId:'',
            title:'',
            body:''
        }
    }

    changeHandler = (e) =>{
        this.setState({[e.target.name]: e.target.value})
    }


    submitHandler = (e) =>{
        e.preventDefault()
        console.log(this.state)
        axios.post("http://localhost:2000/api",this.state).then(response=>{console.log(response)}).catch(error=>(console.log(error)))

    }


    render() {
        const {userId,title,body} = this.state
        return (
            <div>
            <form onSubmit={this.submitHandler}>
                <div>
                    <input type="text" name="userId" value={userId} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="title" value={title} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="body" value={body} onChange={this.changeHandler}/>
                </div>
                <button type="submit">Submit</button>
            </form>
                
            </div>
        )
    }
}

export default PostForm

Upvotes: 0

Views: 760

Answers (2)

Jithin Zachariah
Jithin Zachariah

Reputation: 332

Data can be sent to the backend as URL encoded format or as raw JSON format you have to handle both cases as shown below.

app.use(bodyParser.json({ limit: '10mb' }));
app.use(
  bodyParser.urlencoded({
    limit: '10mb',
    extended: true,
    parameterLimit: 50000
  })
);

Upvotes: 1

Christian LSANGOLA
Christian LSANGOLA

Reputation: 3307

When working with express, by default the req object which represents data or informations coming from your client application doesn't have a body attribute, and that's the reason why your the body attribute is empty.

So if you want to access data sent by your client application through an http request,you should add a middleware function that can parse, inspect the incoming request and takes the whatever data sent by the client via a post or put method http verb, and add it in the body attribute of the request object.That function is executed before your route handler.

If your sending data in a JSON format should add the following middleware:

app.use(express.json()) and your code will look like this :

const express=require('express');

const app=express();

app.use(express.json())

If data is coming in a urlencoded format where you've got a form like this <form method='post' action='http://yourserver/routes_handler'>...</form> without making an ajax request, you will instead add the following middleware:

app.use(express.urlencoded({extended:false})) //it can be true or false depending on what you wan to achieve.

If data can come in the 2 formats then you'll use the both middlewares and your code will look like this:

const express=require('express');

const app=express();

app.use(express.json());
app.use(express.urlencoded({extended:false}));

You don't have to install a third party package like body-parser in order to add the middleware it's already a built-in feature in express

Upvotes: 0

Related Questions