簡體   English   中英

node.js,express和主體解析器中的request.body為空

[英]request.body is empty in node.js, express and body parser

我試圖將請求“發布”到我的節點服務器。

以下是xhttp請求。

let parcel = {
  userId: userId, //string
  unitid: unitid, //string
  selections: selections //array
};

 //Call to the Server
 var oReq = new XMLHttpRequest();
 oReq.addEventListener("load", transferComplete);

 oReq.open("GET", "http://node.server.com/interaction", true);
 //oReq.setRequestHeader('Content-Type', 'application/json');
 oReq.send(parcel);

 function transferComplete(evt) {
     console.log(this.responseText);
 }

這是服務器代碼

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

let app = express();

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

const interaction = require('./routes/interaction');

app.use('/interaction', interaction);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.set("port", process.env.PORT || 5000);

var server = app.listen(app.get('port'), () => {
  console.log("server is started");
});

和交互路由器

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  console.log(req.body)
  res.send(req.body);
});

module.exports = router;

該請求收到響應,但console.log(req.body)返回一個空對象。 我什至檢查了“ req”對象。 該對象中的主體節點也為空。 我要去哪里錯了。 我在哪里可以在服務器中收到包裹對象?

您沒有在客戶端發送任何正文,因此在服務器上沒有收到它也就不足為奇了。

您正在發出一個沒有定義的正文的GET請求。

嘗試使用curl對主體發出請求,然后查看是否進入服務器-這樣一來,您應該消除Express或body解析器出現問題的可能性。 確保使用正確的內容類型。

如果您要發送郵件,請:

  1. 在路由處理程序中使用支持它的HTTP方法(例如POST)
  2. 在客戶端使用相同的HTTP方法
  3. 實際上正確地發送了一些東西

如果直接使用XMLHttpRequest (具有糟糕的API)遇到麻煩,請使用jQuery,瀏覽器請求,SuperAgent,Axios,Got,Request,Reqwest等:

另外,要調試請求中實際發送的數據,請參閱瀏覽器開發人員工具中的“網絡”選項卡,並使用netcat可以很好地了解正在發生的情況:

$ nc -lp 3333

它偵聽端口3333(在這種情況下),並將打印帶有所有標頭和正文的整個請求。 例如,在瀏覽器中訪問http:// localhost:3333 / xxx可能會輸出:

GET /xxx HTTP/1.1
Host: localhost:3333
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,pl;q=0.6
Cookie: io=HQz0J7NwYj76pKf_AAAD

請注意,它不會單獨返回響應,它僅適用於單個請求,因此您需要重新啟動netcat命令以再次對其進行測試。

暫無
暫無

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

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