Fastify 原生只支持 'application/json' 和 'text/plain' content types。默認的字符集是 utf-8。如果你需要支持其他的 content types,你需要使用 addContentTypeParser API。默認的 JSON 或者純文本解析器也可以被更改.
和其他的 API 一樣,addContentTypeParser 被封裝在定義它的作用域中了。這就意味著如果你定義在了根作用域中,那么就是全局可用,如果你定義在一個插件中,那么它只能在那個作用域和子作用域中可用。
Fastify 自動將解析好的 payload 添加到 Fastify request 對象,你能通過 request.body 訪問。
fastify.addContentTypeParser('application/jsoff', function (req, done) {
jsoffParser(req, function (err, body) {
done(err, body)
})
})
// 以相同方式處理多種 content type
fastify.addContentTypeParser(['text/xml', 'application/xml'], function (req, done) {
xmlParser(req, function (err, body) {
done(err, body)
})
})
// Node 版本 >= 8.0.0 時也支持 async
fastify.addContentTypeParser('application/jsoff', async function (req) {
var res = await new Promise((resolve, reject) => resolve(req))
return res
})
你也可以用 hasContentTypeParser API 來驗證某個 content type 解析器是否存在。
if (!fastify.hasContentTypeParser('application/jsoff')){
fastify.addContentTypeParser('application/jsoff', function (req, done) {
// 將請求的主體/payload 解析為特定類型的代碼
})application/jsoff
}
你可以用兩種方式解析消息主體。第一種方法在上面演示過了: 你可以添加定制的 content type 解析器來處理請求。第二種方法你可以在 addContentTypeParser API 傳遞 parseAs 參數(shù)。它可以是 'string' 或者 'buffer'。如果你使用 parseAs 選項 Fastify 會處理 stream 并且進行一些檢查,比如消息主體的 最大尺寸 和消息主體的長度。如果達到了某些限制,自定義的解析器就不會被調(diào)用。
fastify.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) {
try {
var json = JSON.parse(body)
done(null, json)
} catch (err) {
err.statusCode = 400
done(err, undefined)
}
})
你可以看到,新的方法參數(shù)變成了 (req, body, done) 而不是 (req, done)。
查看例子 example/parser.js。
有些情況下你需要捕獲所有的 content type。通過 Fastify,你只需添加'*' content type。
fastify.addContentTypeParser('*', function (req, done) {
var data = ''
req.on('data', chunk => { data += chunk })
req.on('end', () => {
done(null, data)
})
})
在這種情況下,所有的沒有特定 content type 解析器的請求都會被這個方法處理。
對請求流 (stream) 執(zhí)行管道輸送 (pipe) 操作也是有用的。你可以如下定義一個 content 解析器:
fastify.addContentTypeParser('*', function (req, done) {
done()
})
之后通過核心 HTTP request 對象將請求流直接輸送到任意位置:
app.post('/hello', (request, reply) => {
reply.send(request.req)
})
這里有一個將來訪的 json line 對象完整輸出到日志的例子:
const split2 = require('split2')
const pump = require('pump')
fastify.addContentTypeParser('*', (req, done) => {
done(null, pump(req, split2(JSON.parse)))
})
fastify.route({
method: 'POST',
url: '/api/log/jsons',
handler: (req, res) => {
req.body.on('data', d => console.log(d)) // 記錄每個來訪的對象
}
})
關(guān)于輸送上傳的文件,請看該插件。
更多建議: