D
D
Daniil Chashkov2019-06-24 17:28:08
JavaScript
Daniil Chashkov, 2019-06-24 17:28:08

How to get body from post request?

There is a code for sending a post request:

let data = new FormData()
        data["json"] = JSON.stringify(mydata);
        fetch(url, {
            method: 'POST',
            credentials: 'include',
            body: data
        }).then((res)=>{
            // ....
        }).catch(
//....
);

And there is code:
export async function post(req, res, next) {
    console.log(req.body)
    res.writeHead(200, {
        'Content-Type': 'application/json'
    });
}

But when outputting req.body it throws an error (underfined).
How can I get req.body?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2019-06-24
@alexeynobody

Well, depending on what you use on the back-end, if express / koa then there is a body-parser in npm for them. If something else, then I think everything will be about the same there, except that the module will be called differently.
When using it as middleware in routing to this handler, everything will be in req.body

export async function post(req, res, next) {
    console.log(req.body) // вот для этого необходим body-parser
    res.writeHead(200, {
        'Content-Type': 'application/json'
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question