【问题标题】:How to process request headers in Koa.js?如何处理 Koa.js 中的请求标头?
【发布时间】:2018-03-22 15:57:14
【问题描述】:

如何接受application/vnd.api+json的请求内容类型并拒绝其他内容?

另外,我如何使用 Koa.js 访问 x-api-key 值?

提前致谢

【问题讨论】:

  • 你尝试了什么?
  • if (!ctx.accepts('application/vnd.api+json')) { ctx.throw(406, '不支持的内容类型'); } // 但在 Postman 中没有获得状态 406。对于 x-api-key 找不到任何文档
  • 如果您需要帮助,请在您的问题中包含一个完整的、可重现的脚本!
  • 我也尝试过 if (ctx.is(application/vnd.api+json) { .. } 如此处所述github.com/koajs/koa/blob/master/docs/api/request.md 但这对我不起作用,所以我使用了一个简单的比较if (ctx.request.type=='application/vnd.api+json') { .. }

标签: node.js content-type koa.js ctx


【解决方案1】:

获取标题:ctx.get('x-api-key');

【讨论】:

    【解决方案2】:

    这是我对问题第一部分的尝试,内容协商:

    const Koa = require('koa');
    const Router = require('koa-router');
    const app = new Koa();
    const router = new Router();
    
    //const dataAPI = require('../models/traffic');
    
    router.get('/locations/:geohash/traffic/last-hour', (ctx, next) => {    
        // some code for validating geohash goes here ...
    
        if (ctx.request.type=='application/vnd.api+json') {        
            //ctx.body = dataAPI.getTrafficData(ctx.params.geohash, 'hours', 1);
            ctx.body = { status: "success" };
            ctx.type = "application/vnd.api+json";
            next();
        }
        else {
           ctx.throw(406, 'unsupported content-type');
           // actual error will be in JSON API 1.0 format
        }
    });
    

    当我在 Postman 中提交任何不是 application/vnd.api+json 的 Content-Type 值时,我在 Postman 中获得状态 406 Not Acceptableunsupported content-type。否则,我会在正文中得到站 200 OK{ "status": "success"

    已编辑

    还没有找到更好的方法,但下面是一种快速而肮脏的方法来提取x-api-key 的值。它适用于我的目的:

    var key = ctx.request.headers['x-api-key']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-23
      • 2020-05-15
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多