2017-10-11 101 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']