我正在使用主体解析器并为我的前端做出反应。 我正在尝试创建一个用户;下面是前端从后端服务器获取数据的过程:
registering (e) {
e.preventDefault()
let form = e.target
let name = form.querySelectorAll('input')[0].value
fetch('http://localhost:5000/createacc', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'},
mode: 'no-cors',
body: JSON.stringify({name: name})
})
下图是后端接收部分:
function create (req, res, next) {
console.log('req is ...', req.body)
}
目前控制台日志是这样的:
req is ... { '{"name":"Smiley"}': '' }
我将无法正确使用这样的信息,对吧?
是的,您是部分正确的,您收到了一个需要解析的字符串。发送请求时无需使用 JSON.stringify()。 此外,通过发送对象,您应该使用内容类型 application/json。您也可能忘记包含主体解析器中间件。
这是因为
Content-Type
和body
不一致。 Content-Type
表示内容是 x-www-form-urlencoded
但正文格式是 JSON。
如果您想将
Content-Type
保留为 application/x-www-form-urlencoded
,正文格式应类似于 a=xxx&b=yyy
。对于您的代码,它将是:
body: 'name='+name
如果您想将数据传输为 JSON,则应将
Content-Type
更改为 application/json
。
我想分享两个解决方案
"Content-Type": "application/json"
前端:
如果您计划处理更复杂的 formData 或上传文件,那么最好的选择是使用 FormData。你必须为此改变一些事情。
const formData = new FormData();
formData.append('name', name)
...
other things that you might want to add
...
现在要发送的数据类型为“multipart/form-data”。也许您可能不需要明确提及这是前端,但如果出现问题,您可以尝试添加它。
'Content-Type': 'multipart/form-data'
后端:
如果您使用 Node 作为后端框架,那么我们可以使用 multer 来解析 formData。
将其添加到顶部。 当您没有任何要上传的图像或文件时,使用
upload.none()
。
您可以使用 upload.single('name_of_that_field')
上传某些内容,然后从 req.file 访问该内容。您也可以上传多个内容。检查有关此主题的文档或其他答案以获得更清晰的了解
// install multer first
const multer = require("multer");
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.post('/your-route', upload.none(), other middlewares, (req, res) => {
// Now you can access your formData from req.body
// req.body.name for this example will return the name you sent
});