Node.js新手求助:POST请求体显示为{'object Object': ''}问题
嘿,我一眼就看出问题所在啦!你遇到的{'object Object': ''}是因为客户端请求的body格式和你设置的Content-Type不匹配导致的。
问题根源解释
你在客户端设置了Content-Type: application/x-www-form-urlencoded,但直接把userDetails这个JS对象塞进了body里。浏览器遇到这种情况,会默认调用对象的toString()方法,把它转换成字符串"[object Object]"——这也就是服务端收到的奇怪键名的来源。
下面给你两种可行的解决方案:
方案1:保持application/x-www-form-urlencoded格式
把JS对象转换成符合该格式的URL编码字符串,最简单的方式是用URLSearchParams:
const postRegistrationForm = (userDetails, dispatch) => { const url = 'http://localhost:1111/d/register'; const config = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(userDetails) // 这里修改为URLSearchParams实例 }; fetch(url, config) .then(data => data.json()) .then(res => console.log('rezzz is...', res)); };
方案2:改用JSON格式传输(更推荐)
如果你的userDetails是复杂对象(比如嵌套结构),JSON格式会更友好。服务端已经配置了bodyParser.json(),所以只需要修改客户端:
const postRegistrationForm = (userDetails, dispatch) => { const url = 'http://localhost:1111/d/register'; const config = { method: 'POST', headers: { 'Content-Type': 'application/json' // 修改Content-Type为JSON类型 }, body: JSON.stringify(userDetails) // 把JS对象转换为JSON字符串 }; fetch(url, config) .then(data => data.json()) .then(res => console.log('rezzz is...', res)); };
补充说明:你的服务端代码其实没问题,bodyParser.json()和bodyParser.urlencoded()已经同时支持两种格式的解析了,只要客户端调整正确,就能正常拿到请求体啦!
内容的提问来源于stack exchange,提问作者Kayote
相关产品推荐
相关产品推荐

