// this is wrong
app.use(function (ctx, next) {
ctx.set("Access-Control-Allow-Origin", "*");
next();
});
// this is right
app.use(async function (ctx, next) {
ctx.set("Access-Control-Allow-Origin", "*");
await next();
});
koa-bodyparser处理post请求
处理post请求时,我们会遇到一个问题,无论是node的request对象还是koa的request对象,都没办法解析request的body,我们就需要下载并引入一个解析body的中间件koa-bodyparser,koa-bodyparser的具体配置详见下面的说明,这里我们直接放入使用方式。
// 引入路由文件
const index = require('./routes/index.js');
const user = require('./routes/user.js'); // 引入解析request.body的中间件
const bodyparser = require('koa-bodyparser');
// 注册bodyparser,需要注意,bodyparser的注册一定要在router路由注册之前
app.use(bodyparser({
enableTypes:['json', 'form', 'text'] }));
...
// 注册routes
app.use(index.routes(), index.allowedMethods());
app.use(user.routes(), user.allowedMethods());
koa-bodyparser
如上所述,koa-bodyparser用于解析request.body,因为node和koa的request无法解析body。
下载
npm i koa-bodyparser 使用
const bodyparser = require('koa-bodyparser');在注册运行时,bodyparser方法中可传入对象,作相应配置。
– enableTypes:解析器只在配置了enableTypes时解析请求类型,默认是[‘json’, ‘form’]。
– encoding:请求编码,默认是utf-8。
– formLimit:urlencoded body的imit如果主体最终大于此限制,则返回一个413错误代码。默认是56 kb。
– jsonLimit:json主体的限制。默认是1 mb。
– textLimit:文本主体的限制。默认是1 mb。
– strict:当设置为true时,JSON解析器将只接受数组和对象。默认是正确的。参见正文中的严格模式。在严格模式下,ctx.request。body总是一个对象(或数组),这避免了很多类型判断。但文本正文总是返回字符串类型。
– detectJSON:自定义json请求检测函数。默认为null。
app.use(bodyparser({
detectJSON: function (ctx) {
return /.json$/i.test(ctx.path);
}
})); – extendTypes:支持扩展类型
app.use(bodyparser({
extendTypes: {
json: ['application/x-javascript'] // 解析application/x-javascript 类型 作为JSON字符串
}
}));









