Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process request headers in Koa.js?

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

like image 294
Roobie Avatar asked Oct 11 '17 05:10

Roobie


2 Answers

To get the header: ctx.get('x-api-key');

like image 175
Yorkshireman Avatar answered Nov 15 '22 15:11

Yorkshireman


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']
like image 36
Roobie Avatar answered Nov 15 '22 16:11

Roobie