Roo*_*bie 3 content-type node.js koa.js
如何接受请求的内容类型application/vnd.api+json并拒绝其他任何内容?
另外,如何x-api-key使用Koa.js 访问值?
提前致谢
这是我对问题的第一部分,内容协商的尝试:
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
}
});
Run Code Online (Sandbox Code Playgroud)
当我在Postman中提交Content-Type的值而不是application / vnd.api + json的任何内容时,我都处于状态406 Not Acceptable和unsupported content-typePostman中。否则,我得到站200 OK和{ "status": "success"在体内。
已编辑
还没有找到更好的方法,但是下面是提取的值的快捷方法x-api-key。它适用于我的目的:
var key = ctx.request.headers['x-api-key']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6093 次 |
| 最近记录: |