eggjs / egg

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa
https://eggjs.org
MIT License
18.88k stars 1.81k forks source link

在中间件中 ctx.response.headers.hasOwnProperty 为 undefined #1068

Closed runfan closed 7 years ago

runfan commented 7 years ago

我在创建中间件的时候,发现 ctx.response.headers.hasOwnProperty 是 undefined 但是typeof ctx.response.headers 结果是object

我的代码是

module.exports = options => {
  return async function (ctx, next) {
    console.log('====================',typeof ctx.response.headers);
    console.log('====================',typeof ctx.response.headers.hasOwnProperty);
    await next();
  };
};

config.default.js中的配置内容

{
    match: '/api',
}
JacksonTian commented 7 years ago

这很正常的,任何一个 Object.create(null) 创建的对象,都没有这个方法。

chenyulun commented 7 years ago

搞不懂为什么用这种方式创建response.headers,然而request.headers也有proto, response.headers就没有? 现在我使用egg-oauth2-server,里面有一段代码

// Store the headers in lower case.
  for (var field in options.headers) {
    if (options.headers.hasOwnProperty(field)) {
      this.headers[field.toLowerCase()] = options.headers[field];
    }
  }
atian25 commented 7 years ago

直接说你的场景吧。

那几个对象是 koa 自带的吧。

chenyulun commented 7 years ago

想试试这个使用 Egg 快速开发 OAuth 2.0 授权服务; 里面使用到/Users/tusm/github/mygithub/egg-cms/node_modules/oauth2-server/lib/response.js的这个方法;导致接口返回{"error":"options.headers.hasOwnProperty is not a function"}

其实我也不明白你们谁应该修改这个场景; 感觉他这样写是多此一举,具体我猜不出来他这样写是为了避免什么问题?

atian25 commented 7 years ago

for...in 里面放 hasOwnProperty 是 ES6 之前的推荐编码风格之一,应该改为 for...of

@Azard 你的锅么?

Azard commented 7 years ago

这个是 https://github.com/oauthjs/node-oauth2-server/blob/master/lib/response.js 的写法,不是我包装的插件里写的。

egg.js 的 ctx.response.header 本来就没有 hasOwnPropertyhttps://github.com/Azard/egg-oauth2-server/issues/11 现在应该不需要用 hasOwnProperty 了。

atian25 commented 7 years ago

所以修复下? 或者在上层插件里面 hot fix 下.

chenyulun commented 7 years ago

也有人给node-oauth2-server提了hasOwnProperty不存在问题 但是他的代码好像很久没改了,没采纳!!! @Azard 重新创建对象传进去就好了,后还是有问题,按照这个oauth2-server.test.js 请求/user/authenticate 返回Server error: accessTokenExpiresAt must be a Date instance 我放弃了,我还是研究一下session和cookie吧

atian25 commented 7 years ago

不靠谱的,维护不及时的库,不应该使用。

chenyulun commented 7 years ago

我之前说 typeof request.headers.proto //Obeject response.headers.proto //undefined 能不能帮忙看看是不是koa的问题,他为什么这么作? 接下来的问题我在egg-oauth2-server提问, 我觉得你们回复那么快我又还原了代码,接着搞一会

thonatos commented 7 years ago

这个问题不是 egg 的,我们在那边讨论。

JacksonTian commented 7 years ago

这种东西本来就是为了避免安全问题而特意使用 Object.create(null) 的。