簡體   English   中英

req.body 用 express 未定義

[英]req.body undefined with express

我在我的發布請求中得到了一個未定義的 req.body,嘗試了一切,從 body-parser 到 express.json,兩者都在一起(肯定不好),但仍然無法讓它工作。 任何幫助都非常感謝!

我已將我的 nodejs 服務器減少到最低限度:

const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/requests', (req, res) => {
    console.log(req.body);
    res.status(201).json('all ok');
  })

app.listen(4000, () => {console.log('Server listening on port 4000')});

我的請求是(使用 VS Code 的 REST 客戶端完成):

POST http://localhost:4000/requests
Content-Type: 'application/json'

{
  "msg":"Some message",
  "other":"Other msg"
}

我正在使用 curl,即使使用節點12.22.9也可以在這里使用,很確定您只是忘記在頂部聲明 express 或者您的 rest 客戶端有問題

curl -X POST http://localhost:4000/requests -H 'Content-Type: application/json' -d '{"msg":"Some message","other":"Other msg"}'

.js

const express = require('express')
const app = express()

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/requests', (req, res) => {
    console.log(req.body);
    res.status(201).json('all ok');
  })

app.listen(4000, () => {console.log('Server listening on port 4000')});

package.json

{
  "dependencies": {
    "body-parser": "^1.19.1",
    "express": "^4.17.2"
  }
}

就像這里其他迷失靈魂的信息一樣......

如果您在 windows 系統上使用 REST 客戶端應用程序,請確保您的請求沒有上限。 我的情況:

POST http://localhost:4000/requests/
content-type: application/json

{
  "msg":"Some message",
  "other":"Other msg"
}

並且(也是我的錯誤):不要將 application/json 放在任何類型的引號中,簡單明了!

(我確實從win和mac機器上做了請求,都沒有工作,但這就是原因!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM