0
以下是向我的服务器请求POST数据的JavaScript代码。当我打印出身体数据时,似乎工作正常,但Koa甚至没有从请求中解析“身体”(使用koa-bodyparser)。我不知道为什么会发生这种情况,它的工作原理与一周前相似。Koa不会从获取POST请求中解析“body”
浏览器
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)
}
})
只要确认一下,检查一下'koa-bodyparser'的'app.use(bodyParser())'调用是否在'app.use(router.routes())'之上。 – saadq
@saadq这是问题谢谢! –