我有一个快速演示服务器,可以回显客户端向其发送的内容。
它用于学习事件,客户端将使用 fetch API 进行 POST,例如:
fetch('http://localhost:5000/', {
method: 'POST',
body: JSON.stringify({ lab: 'fetch', status: 'fun' }),
headers: messageHeaders
})
数据的body
将是字符串、JSON或FormData
.
我对 Express 不太熟悉,但我只想有一个处理所有三种 body
类型的路由。目前我不知道该怎么做。
我从 this SO post 开始,但该解决方案不适用于我的情况 - 我不认为 res.format API 允许我访问请求的正文,但它似乎也不适用于多部分表单数据。
相反,我默认使用 body-parser
和 multer
潜在的中间件黑客配置中的软件包:
// if client POST body is a string, parse as text
app.post('/', bodyParser.text(), (req, res, next) => {
const contentType = req.get('content-type');
if (!contentType.includes('text/plain')) {
return next();
}
res.write(JSON.stringify(req.headers, null, 2))
res.write('\n\n')
res.write(req.body)
res.end()
});
// if client POST body is JSON, parse as JSON
app.post('/', bodyParser.json(), (req, res, next) => {
const contentType = req.get('content-type');
if (!contentType.includes('application/json')) {
return next();
}
res.write(JSON.stringify(req.headers, null, 2))
res.write('\n\n')
res.write(JSON.stringify(req.body, null, 2))
res.end()
});
// if client POST body is FormData, parse as form-data
app.post('/', upload.fields([]), (req, res, next) => {
const contentType = req.get('content-type');
if (!contentType.includes('multipart/form-data')) {
return next();
}
res.write(JSON.stringify(req.headers, null, 2))
res.write('\n\n')
res.write(JSON.stringify(req.body, null, 2))
res.end()
});
是否有更标准或“更好”的模式来实现此功能?也许我只需要编写一个处理程序?
最佳答案
更干净的解决方案可能是将中间件作为数组传递到特定路由,它最终会被解析。
app.post('/notes', [urlencodedParser, multiPart.array("files", 5)], (req, res)=> {
//do what you want
console.log(req.files);// to get the files
console.log(req.body);// to get the body
})
但是,您可以使用 app.use(middleware:parser);
但请注意,这样,将为应用程序中由 Express 处理的所有路由调用中间件函数。
所以我认为在需要这种动态的特定路线上处理它会更简洁,并且可能具有更好的性能。
关于javascript - 在单个快速处理程序中处理 multipart/formdata、application/json 和 text/plain?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784509/