【问题标题】:Express POST request from react return empty object来自反应的快速 POST 请求返回空对象
【发布时间】:2021-07-24 13:36:47
【问题描述】:

我正在尝试从客户端应用程序发送对象数据,但它不返回服务器端只返回一个空对象。我没有错误,并且在控制台中提交后。

客户端使用这个:

const url = `http://localhost:5000/addUser`;
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    }).then(res => console.log(res))

我使用的服务器端:

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
require("dotenv").config()
const port = process.env.PORT || 5000;
const { MongoClient } = require('mongodb');

const app = express()
app.use(cors())
app.use(express.json())
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
app.post('/addUser', (req, res) =>{
const newUser = req.body;
console.log('added new user', newUser)
})

服务器端 package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
 "start": "nodemon index.js",
 "test": "echo \"Error: no test specified\" && exit 1"
},
 "author": "",
 "license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongodb": "^3.6.10",
"nodemon": "^2.0.10"
 }
}

【问题讨论】:

    标签: node.js reactjs mongodb express


    【解决方案1】:

    您的问题有点含糊,但我认为问题在于您在客户端上的 .then(res => console.log(res)) 没有记录新用户。

    您的服务器实际上并没有发送回复。再次阅读 Express 文档,但基本上它看起来像这样:

    app.post('/addUser', (req, res) =>{
        const newUser = req.body;
        console.log('added new user', newUser);
        // Send HTTP status code 200 back, with the `newUser` in JSON format as body
        res.status(200).json(newUser);
    })
    

    【讨论】:

    • 这个问题已经解决了。我的nodeJs版本旧,当我安装新版本时,它就解决了。谢谢你的回答。
    • 非常出乎意料的是,简单地升级 NodeJS 就解决了这个问题 _(在我看来,你的代码似乎不应该返回任何东西),但至少你让它工作了。
    猜你喜欢
    • 2019-01-05
    • 2018-01-14
    • 2019-02-14
    • 1970-01-01
    • 2021-12-12
    • 2020-06-25
    • 2021-05-13
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多