簡體   English   中英

Koa不會從提取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)
    }
})

這應該工作...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM