前言

大多时候,我们希望使用请求头中的Accept字段来确定我们接口返回的数据类型,来满足不同格式需求的调用者(防止解析错误)。
当然还有 字符集、编码、语言等等。
使用accepts包我们就可以解决这个问题。
如果没有符合的数据类型,就直接返回 HTTP 406 “Not Acceptable” 错误来告知调用者;

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var accepts = require('accepts')
var http = require('http')

function app (req, res) {
var accept = accepts(req) // 使用request对象创建实例

switch (accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}

res.end()
}

http.createServer(app).listen(3000) // 创建服务

总结

  1. 同样我们可以应用Express,Koa框架中;
  2. 在Express中,Accept判断已经被封装到了**req.accepts()**方法中,直接使用就可以了;
  3. 其他请求头类型判断同理;