我刚刚开始使用 Fastify,遇到了一个问题,我开始创建一个获取请求以通过其标题获取项目,但当我尝试和时,它总是给我 null
的响应记录 request.body
。
我的获取请求:
// Get points by title
fastify.route({
method: 'GET',
url: '/pointz/title',
handler: (request, reply) => {
return request.body
}
})
我在 postman 中的获取请求(作为代码):
curl --location --request GET 'http://localhost:3000/pointz/title' \
--header 'Content-Type: application/json' \
--data-raw '{
"title": "test"
}'
Screenshot of my input and output in Postman
预期的结果是请求返回一个包含正在发送的 JSON 的正文,因此我可以更改代码以访问 request.body.title
,返回值为 测试
。
更新: 暂时找到了解决方法。如果我将 GET 请求更改为 POST 请求,它就会像预期的那样工作。然而我质疑这是否被认为是好的做法。
最佳答案
正如本 GitHub 问题中所讨论的 GET request validated scheme body?
body
不应在 GET 请求中发送,a datailed answer about it
并且 fastify 默认忽略它。
但是遗留代码确实如此,如果您需要支持它,则必须使用原始请求:
const fastify = require('fastify')({ logger: true })
fastify.get('/', async (req) => {
let body = ''
for await (const data of req.raw) {
body += data.toString()
}
return body
})
fastify.listen(3000)
然后您的 curl
命令将按预期工作。
const got = require('got')
got.get('http://localhost:3000/', {
json: { hello: 'world' },
allowGetBody: true
}).then(res => {
console.log('Returned = ' + res.body)
})
关于Fastify 按标题获取项目始终将原始 JSON 返回为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63783098/