ctx 请求正文未用 nodejs 定义
ctx request body is undefined with nodejs
我有一个问题,当我 post 我的表格时,我无法在 API.
中获取 post 中的内容
这是我的 post 反应中的 axios :
onSubmit = () => {
let data = {
nickname: this.state.nickname,
password: this.state.password
}
axios.post("/api/user/login", { data })
.then(res => {
console.log("res from api is => ", res.data);
})
}
这是我的 API :
从 "koa-body" 导入 koaBody;
const app = new koa();
const router = new Router();
app.use(router.routes());
app.use(koaBody());
router.post("/api/user/login", async(ctx) => {
console.log("body is => ", ctx.request.body);
ctx.body = "ok";
});
问题是 ctx.request.body 总是未定义...
你能告诉我为什么吗 ?
我试过 router.get 没问题,它工作正常。
您需要在路由器之前加载正文解析器,否则路由器将在正文内容被解析之前处理请求:
app.use(koaBody());
app.use(router.routes());
我有一个问题,当我 post 我的表格时,我无法在 API.
中获取 post 中的内容这是我的 post 反应中的 axios :
onSubmit = () => {
let data = {
nickname: this.state.nickname,
password: this.state.password
}
axios.post("/api/user/login", { data })
.then(res => {
console.log("res from api is => ", res.data);
})
}
这是我的 API :
从 "koa-body" 导入 koaBody;
const app = new koa();
const router = new Router();
app.use(router.routes());
app.use(koaBody());
router.post("/api/user/login", async(ctx) => {
console.log("body is => ", ctx.request.body);
ctx.body = "ok";
});
问题是 ctx.request.body 总是未定义... 你能告诉我为什么吗 ? 我试过 router.get 没问题,它工作正常。
您需要在路由器之前加载正文解析器,否则路由器将在正文内容被解析之前处理请求:
app.use(koaBody());
app.use(router.routes());