Koa 不从 fetch POST 请求中解析 'body'

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

这是向我的服务器请求 POST 数据的 javascript 代码。当我打印出正文数据时,它似乎工作正常,但 Koa 甚至没有从请求中解析 'body'(使用 koa-bodyparser)。我不知道为什么会这样,它确实像一周前一样有效。

浏览器

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)
        }
    })

})

服务器

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)
    }
})

您需要使用co-body解析发布的数据:

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)
    }
})

这应该有效...