Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch POST method gives empty body on Express server

I make a POST request from my browser client:

const post = async (url, body) => {
        try {
            const response = await fetch(url, {
                method: `POST`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body
            });
            return response.json();
        } catch (error) {
            console.log(error.stack);
        }
    }
const data = await post(`http://localhost:4050/analyze`, { text });

And I handle it on Express server with this setup:

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

This is my route:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

router.post(`/`, errorHandler(async (req, res, next) => {
    const { text } = req.body;
    console.log(req.body)

    const value = await analyze(text);

    res.json({ rephrased });
}));

The console.log shows me this:

{ 'object Object': '' }

Why fetch method gives me Object instead of text property?

UPDATE:
When I do Stringify:

        method: `POST`,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify(body)

The body became like this and console.log shows:

{ '{"text":"asdfasdf"}': '' }

>Solution :

You are passing fetch a plain object for the body and it doesn’t know what to do with it, so it calls .toString() and gives you nothing useful.

Pass it a URLSearchParams object instead. (Here I assume text is a string)

const body = new URLSearchParams();
body.append("text", text);

This will convert to a application/x-www-form-urlencoded string.

(You can also omit the headers as fetch can infer the correct Content-Type from the URLSearchParams object.)


Re edit: JSON.stringify will encode the data as JSON. JSON is not application/x-www-form-urlencoded.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading