【发布时间】:2018-09-04 16:50:37
【问题描述】:
我已经定义了我的自定义中间件,如下所示。它基本上获取 urlencoded 表单参数并将 urlencoded 字符串设置到标头中以供以后使用。我不得不走这条路,因为对于application/x-www-form-urlencoded 类型的请求,只有koa-bodyparser 支持获取带有表单参数的原始urlencoded 字符串。但是,由于它不支持文件,我无法使用它。
我的中间件定义如下:
const rawBody = require('raw-body')
const contentType = require('content-type')
function rawUrlEncodedFormData() {
return async function setUrlEncodedHeader(ctx, next) {
if (ctx.path === '/v1/urlencoded') {
const rawRequestBody = await rawBody(ctx.req, {
length: ctx.get('content-length'),
encoding: contentType.parse(ctx.req).parameters.charset,
})
const urlEncodedString = rawRequestBody.toString('utf-8')
console.log('form urlencoded params:', urlEncodedString)
ctx.set('urlencoded-form-string', urlEncodedString)
await next()
}
await next()
}
}
module.exports = rawUrlEncodedFormData
然后我将它与其他中间件一起使用,例如:
const middlewares = () =>
koaCompose([
Cors(),
requestId(),
logger(log),
responseTime({
logger: log,
}),
rawUrlEncodedFormData(),
koaBody({
multipart: true,
}),
redis({
redisURL: config.redis.url,
}),
authorize(),
])
module.exports = middlewares
但是,当我向该端点发出调用时: 1. urlencoded 表单参数字符串获取正确。 2.请求(和应用程序)刚刚挂起
我有什么遗漏吗?注册到该路由的控制器函数根本不会被调用。我收到以下错误
"请求中止","name":"BadRequestError","stack":"BadRequestError: 请求在 IncomingMessage.onAborted 处中止\n
【问题讨论】:
-
如果删除 koaBody 会发生什么?
-
@evert 感谢您的评论...我收到以下错误:
Error","stack":"Error: next() called multiple times\n试图找出原因 -
查看中间件中的 if 语句。如果 if 条件为真,您将在中间件中调用
await next(),然后立即调用。
标签: javascript middleware koa koa-bodyparser