gpt4 book ai didi

javascript - 在单个快速处理程序中处理 multipart/formdata、application/json 和 text/plain?

转载 作者:行者123 更新时间:2023-11-29 23:24:04 25 4
gpt4 key购买 nike

我有一个快速演示服务器,可以回显客户端向其发送的内容。

它用于学习事件,客户端将使用获取 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-parsermulter潜在中间件黑客配置中的包:

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com