0

Everytime I am sending a POST request (fetch) with body containing the state of the app. I am getting a empty object on the serve side. What is wrong here? I am supposed to get the object with name, username and password.

Console's output

You are listening to port 4000
{}
{}

The server's code

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', (req, res)=> {
    res.json({ip: req.connection.remoteAddress});
})

app.post('/post', (req,res)=> {
    console.log(req.body);
    res.json({a: "hello"})
})

app.listen(4000, "0.0.0.0",()=> {
    console.log("You are listening to port 4000")
});

The client's code

import React from "react";

class Form extends React.Component{
    constructor() {
        super();
        this.state = {
            name: '',
            username: '',
            password: ''
        }
    }

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

    handleSubmit =  async (e) => {
        e.preventDefault();
        let res = await fetch('http://localhost:4000/post', {
            mode: 'cors',
            method: 'POST',
            headers: { 
                "Content-type": "application/json; charset=UTF-8"
            },
            body: JSON.stringify(this.state)
        });
        console.log(res);
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <div>
                    <legend>Name</legend>
                    <input value={this.state.name} onChange={this.handleChange} name='name' type='text'></input>
                </div>
                <div>
                    <legend>Username</legend>
                    <input value={this.state.username} onChange={this.handleChange} name='username' type='text'></input>
                </div>
                <div>
                    <legend>Password</legend>
                    <input value={this.state.password} onChange={this.handleChange} name='password' type='password'></input>
                </div>
                <button>Submit</button>
            </form>
        )
    }
}


export default Form;

2 Answers 2

2

It looks like you use req.params in the post endpoint. req.params is used to capture route parameters. You need to use req.body to get the body of the POST request.

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', (req, res)=> {
    res.json({ip: req.connection.remoteAddress});
})

app.post('/post', (req,res)=> {
    console.log(req.body);
    res.json({a: "hello"})
})

app.listen(4000, "0.0.0.0",()=> {
    console.log("You are listening to port 4000")
});
Sign up to request clarification or add additional context in comments.

2 Comments

add app.use(bodyParser.json()); and try again
FYI, there is no need to separately import body-parser. express.json() and express.urlencoded() are already available and are built-into express (which uses body-parser to implement them).
2

you're sending a JSON body, you need to add a json bodyparser

app.use(bodyParser.json());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.