Node.js 节点在';相等';标志=

Node.js 节点在';相等';标志=,node.js,reactjs,Node.js,Reactjs,我在React客户端(localhost:3000)上从FBAPI接收用户对象。 然后我将它发送到我的节点服务器(localhost:4000) 当在节点路由上接收到对象并记录它时,它将拆分任何带有“=”符号的值(冒号和空格)。这破坏了我的JSON对象 从客户端发送的原始对象:(问题在于imageUrl键等号) 这是我在节点服务器中获得它的方式:(转到'asid':…) 路由器功能: router.post("/post-test", (req, res, next) => { c

我在React客户端(localhost:3000)上从FBAPI接收用户对象。 然后我将它发送到我的节点服务器(localhost:4000) 当在节点路由上接收到对象并记录它时,它将拆分任何带有“=”符号的值(冒号和空格)。这破坏了我的JSON对象

从客户端发送的原始对象:(问题在于imageUrl键等号)

这是我在节点服务器中获得它的方式:(转到'asid':…)

路由器功能:

router.post("/post-test", (req, res, next) => {
    console.log("hi amit POST")
    console.dir(req.body)
    res.end()
})
从客户端发送的请求:

axios.post("http://localhost:4000/post-test", user, {
                    headers: {"Content-Type": "application/x-www-form-urlencoded"}
                })
                .then(res => {})
                .catch(err => {
                    console.log(err)
                })
这就像打破字符串来查询参数,但我只希望它是一个字符串

axios.post("http://localhost:4000/post-test", user, {
  headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
这里,您告诉服务器您正在发送
formurlencoded
数据。URL编码的数据遵循
key=value&key2=value2
格式。服务器看到内容类型头并尝试将JSON解析为URL编码的数据

将内容类型更改为JSON类型:

axios.post("http://localhost:4000/post-test", user, {
  headers: {"Content-Type": "application/json"}
})

您发送的标头不正确,导致服务器错误地解析值

改变
{“内容类型”:“应用程序/x-www-form-urlencoded”}


{“Content Type”:“application/json”}

我假设您使用的是带主体解析器的express。 为了使它与JSON一起工作,请考虑以以下方式引导应用程序:

服务器 客户 有效载荷 结果
向我们展示路由处理程序代码和客户端代码。添加的代码段现在我得到的是空对象:{}您需要在路由之前添加主体解析器中间件:
router.use(bodyParser.json())
。如果不清楚,请参见这里的示例:我没有使用bodyparser,因为它不再需要了,因为express内置了它,但我错过了添加这个中间件(它取代了bodyparser):app.use(express.json())现在可以工作了。谢谢
axios.post("http://localhost:4000/post-test", user, {
  headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
axios.post("http://localhost:4000/post-test", user, {
  headers: {"Content-Type": "application/json"}
})
const express = require("express")
const bodyParser = require('body-parser')
const app = express();

app.use(bodyParser.json());
axios.post("http://localhost:4000/post-test", user, {
  headers: {"Content-Type": "application/json"}
});
{
  "about": "abcde",
  "age": 26,
  "email": "test@test.com",
  "fbProfileLink": "www.some-profile-link-here.com",
  "gender": "male",
  "id": null,
  "imageUrl": "https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash",
  "language": {
    "mainLang": "",
    "speaksEnglish": true
  },
  "name": "abcde",
  "residence": "abcde"
}
hi amit POST
{ about: 'abcde',
  age: 26,
  email: 'test@test.com',
  fbProfileLink: 'www.some-profile-link-here.com',
  gender: 'male',
  id: null,
  imageUrl:
   'https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash',
  language: { mainLang: '', speaksEnglish: true },
  name: 'abcde',
  residence: 'abcde' }