如何接受内容类型为application/vnd.api+json的请求并拒绝其他类型的请求?
另外,如何使用Koa.js访问x-api-key值?
提前感谢
发布于 2018-10-30 22:28:15
要获取标头:ctx.get('x-api-key');
发布于 2017-10-12 10:07:56
这是我对问题的第一部分,内容协商的尝试:
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
}
});否则,我将在主体中获得工作站200 OK和{ "status": "success"。
编辑的
我还没有找到更好的方法,但下面是一种快速而肮脏的方法来提取x-api-key的值。它为我的目的而工作:
var key = ctx.request.headers['x-api-key']https://stackoverflow.com/questions/46680358
复制相似问题