Home > Software engineering >  Fetch POST method gives empty body on Express server
Fetch POST method gives empty body on Express server

Time:01-31

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:

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"}': '' }

CodePudding user response:

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.

  • Related