Home > front end >  Fetch Post a number server body undefined
Fetch Post a number server body undefined

Time:10-17

On the server I can't get my request.body.value but I don't know why. It is always undefined. I have already tried my other fetch function with a json. And it has worked and they are very similar.

app.use(express.urlencoded({
    extended: true
}));  
app.post('/async', (request, response) => {
    const size = request.body;
    console.log(size.value)
    let data = [];
    for (let i = 0; i < size.value; i  ) {
        data.push(faker.fake("{{name.lastName}}"   " "   "{{name.firstName}}"))
    }
    response.send(JSON.stringify(data))
})
async function sendAsync(event) {
            event.preventDefault();
            let value = 15;
            let response = await fetch('/async', {
                method: "post",
                body: value
            });
            if (!response.ok) throw new Error(response.statusText);
            let name = await response.json();
            displayUserInfo(name);
        }

CodePudding user response:

your request.body is the whole value you sent body: value. it's not an object

1- deal with it as a value directly

app.post('/async', (request, response) => {
    const size = request.body;
    console.log(size) // here
    let data = [];
    for (let i = 0; i < size; i  ) { //here
        data.push(faker.fake("{{name.lastName}}"   " "   "{{name.firstName}}"))
    }
    response.send(JSON.stringify(data))
})

or 2- send an object that has a property called value with the value you want

async function sendAsync(event) {
            event.preventDefault();
            let value = 15;
            let response = await fetch('/async', {
                method: "post",
                body: {value} //here
            });
            if (!response.ok) throw new Error(response.statusText);
            let name = await response.json();
            displayUserInfo(name);
        }

  • Related