您需要更改方法,因为默认内容解析器不管理压缩并将尝试解析body
.
因此,要管理压缩,您可以覆盖默认值addContentTypeParser
并添加解压缩逻辑:
const zlib = require('zlib')
const port = 8081
var fastify
fastify = require('fastify')({ logger: true })
/**
* Setup an fastify server and define port to listen all incoming requests for this application
*/
const setUpFastify = () => {
fastify.addContentTypeParser('application/json', { parseAs: 'buffer' }, function (req, body, done) {
if (req.headers['content-encoding'] && req.headers['content-encoding'] === 'gzip') {
zlib.gunzip(body, function (err, dezipped) {
if (err) {
done(err, null)
} else {
done(err, JSON.parse(dezipped.toString('utf-8')))
}
})
} else {
done(null, JSON.parse(body.toString('utf-8')))
}
})
fastify.post('/track', function (req, reply) {
reply.send(req.body)
})
fastify.listen(port, 'localhost', () => {
console.log('Worker listening on ' + port + ` PID: ${process.pid}`)
})
}
setUpFastify()
请注意,fastify 用于secure-json-parse
解析 json 字符串。
和卷曲,注意--data-binary
:
curl --request POST \
--url http://127.0.0.1:8081/track \
--header 'Accept: */*' \
--header 'Accept-Encoding: gzip, deflate' \
--header 'Connection: keep-alive' \
--header 'Content-Encoding: gzip' \
--header 'Content-Length: 739' \
--header 'Content-Type: application/json' \
--header 'Host: 127.0.0.1:8081' \
--data-binary @package.json.gz
PS 尝试 curl ,@
发送的有效负载为 1 字节长度