How to accept request content-type of application/vnd.api+json
and reject anything else?
Also how can I access the x-api-key
value using Koa.js ?
Thanks in advance
To get the header: ctx.get('x-api-key');
This is my attempt to the first part of the question, content negotiation:
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
}
});
I am getting status 406 Not Acceptable
and unsupported content-type
in Postman when I submit the value for Content-Type in Postman anything that is not application/vnd.api+json. Otherwise, I get station 200 OK
and { "status": "success"
in the body.
Edited
Haven't found a better to this but below is a quick and dirty way to extract the value of x-api-key
. It works for my purpose:
var key = ctx.request.headers['x-api-key']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With