Search code examples
javascriptnode.jsfetchkoakoa2

Koa doesn't parse 'body' from fetch POST request


Here's the javascript code that request POST data to my server. when I print out the body data, It seems works fine, but Koa doesn't even parse 'body' from the request(using koa-bodyparser). I have no idea why this happens, It literally worked like a week ago.

Browser

jQuery(document).ready(function($) {
    $(".mypage_container .btn-block").click(async() => {
        let payload = {
            email: $('#username').val(),
            password: $('#password').val(),
            country: $('#CountriesDropDownList').val(),
            firstname: $('#firstname').val(),
            lastname: $('#lastname').val(),
            gender: checkGender(),
            address1: $('#address1').val(),
            zipcode: $('#zipcode').val(),
            mobile: $('#mobile').val(),
            newsletter: newsLetter()
        }

        let option = {
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }

        try {
            let res = await fetch('/signup', option)
        } catch (e) {
            console.error("failed to send signup request", e)
        }
    })

})

Server

router.post('/signup', async (ctx, next) => {
    let data = ctx.request.body

    console.log(ctx.request.body, ctx.request) // says undefined on first variable, request info without 'body' from the request.
    try {
        let user = new User(data)
        await user.save()
        ctx.body = data
    } catch (e) {
        console.error(e)
    }
})

Solution

  • You need to use co-body to parse the posted data:

    const parse = require('co-body');
    
    router.post('/signup', async (ctx, next) => {
        let data = await parse(ctx);
        console.log(data);
        try {
            let user = new User(data)
            await user.save()
            ctx.body = data
        } catch (e) {
            console.error(e)
        }
    })
    

    This should work ...