不使用express包,如何在Nuxt.js ServerMiddleware中获取POST数据?
不使用Express在Nuxt ServerMiddleware中获取POST数据
前端发送POST数据
发送JSON格式数据
用fetch发送JSON格式请求,需设置Content-Type为application/json,并将数据转为JSON字符串:
async function submitJsonData() { const payload = { username: 'Ki_Ki', email: 'test@example.com' } const res = await fetch('/api/handle-json', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }) const result = await res.json() console.log('返回结果:', result) }
发送表单格式数据
发送x-www-form-urlencoded格式的表单数据,可直接用URLSearchParams构造请求体:
async function submitFormData() { const formParams = new URLSearchParams() formParams.append('username', 'Ki_Ki') formParams.append('email', 'test@example.com') const res = await fetch('/api/handle-form', { method: 'POST', body: formParams }) const result = await res.json() console.log('返回结果:', result) }
ServerMiddleware处理逻辑
Nuxt的ServerMiddleware基于Node.js原生http模块,可通过监听请求流的data和end事件获取请求体,再根据格式解析数据。
处理JSON格式请求
创建server-middleware/json-handler.js:
export default (req, res) => { // 只响应POST请求 if (req.method !== 'POST') { res.writeHead(405, { 'Content-Type': 'application/json' }) return res.end(JSON.stringify({ error: '仅支持POST请求' })) } let requestBody = '' // 拼接请求体数据流 req.on('data', (chunk) => { requestBody += chunk.toString() }) // 数据流接收完毕,解析数据 req.on('end', () => { try { const postData = JSON.parse(requestBody) res.writeHead(200, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ success: true, message: '数据接收成功', receivedData: postData })) } catch (err) { res.writeHead(400, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ error: 'JSON格式错误' })) } }) }
处理表单格式请求
创建server-middleware/form-handler.js:
export default (req, res) => { if (req.method !== 'POST') { res.writeHead(405, { 'Content-Type': 'application/json' }) return res.end(JSON.stringify({ error: '仅支持POST请求' })) } let requestBody = '' req.on('data', (chunk) => { requestBody += chunk.toString() }) req.on('end', () => { try { const formData = new URLSearchParams(requestBody) // 转换为普通对象方便使用 const postData = Object.fromEntries(formData) res.writeHead(200, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ success: true, message: '表单数据接收成功', receivedData: postData })) } catch (err) { res.writeHead(400, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ error: '表单格式错误' })) } }) }
配置ServerMiddleware
在nuxt.config.js中注册上述中间件:
export default { // ...其他配置 serverMiddleware: [ { path: '/api/handle-json', handler: '~/server-middleware/json-handler.js' }, { path: '/api/handle-form', handler: '~/server-middleware/form-handler.js' } ] }
注意事项
- 若需处理大文件或
multipart/form-data格式,原生Node.js处理较为繁琐,可考虑使用轻量库(如formidable);普通数据场景下,上述方法足够 - 可添加请求体长度限制,避免恶意大请求占用服务器资源
内容的提问来源于stack exchange,提问作者Ki_Ki
相关产品推荐
相关产品推荐

