2017-10-11 99 views
0

如何接受请求内容类型application/vnd.api+json并拒绝其他任何内容?如何在Koa.js中处理请求标头?

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

在此先感谢

+0

你试过什么? – Evert

+0

if(!ctx.accepts('application/vnd.api + json')){ctx.throw(406,'unsupported content-type'); } //但邮递员没有获得状态406。对于x-api-key找不到任何文档 – Roobie

+0

如果您需要帮助,请在您的问题中包含一个完整的,可重现的脚本! – Evert

回答

0

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

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 
    } 
}); 

我得到的邮差状态406 Not Acceptableunsupported content-type当我提交值内容 - 在邮递员中输入任何不是application/vnd.api + json的东西。否则,我会在车站内找到200 OK{ "status": "success"

编辑

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

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