如何在json-server请求中找到request.headers?

时间:2017-10-05 10:03:10

标签: mocking http-headers json-server

我尝试让我的模拟API(json-server)以一种方式响应,如果客户端在其请求的标头中发送了AUTH_TOKEN,并且如果他没有。这段代码是我使用的,它来自json-server docs。

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use((req, res, next) => {
 if (isAuthorized(req)) { // add your authorization logic here
   next() // continue to JSON Server router
 } else {
   res.sendStatus(401)
 }
})
server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})

当然这是有效的,除了isAuthorized(req)函数需要检查请求标头。我的isAuthorized函数如下所示(伪)。

const isAuthorized = (req) => {
  return req.getHeader('AUTH_TOKEN') ? true : false;
}

这不起作用,因为req没有getHeader方法,但我的意图很明确 - 我需要检查令牌,如果它存在则返回true,否则假的。

我怎样才能做到这一点?

req.headers返回以下内容。

{
  host: 'localhost:3000',
  map: '[object Object]',
  'if-none-match': 'W/"a...........5r/3c"',
  accept: 'application/json, text/plain, */*',
  'user-agent': 'App/1 CFNetwork/887 Darwin/16.7.0',
  'accept-language': 'en-us',
  'accept-encoding': 'gzip, deflate',
  connection: 'keep-alive'
}

与我在实际请求中发送的标头实际上没有任何关系。

1 个答案:

答案 0 :(得分:2)

下面是使用expressjs。 查看他们的文档(https://expressjs.com/en/4x/api.html),好像您可以使用req.get('Header name here')