簡體   English   中英

使用http.post時,Express req.body為空

[英]Express req.body is empty when using the http.post

我不知道為什么req.body是EMPTY ... app.js使用body-parser中間件( http://www.expressjs.com.cn/4x/api.html#req.body

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// add baseurl
app.use('/api', index);
app.use('/api', users);

user.js的

router.route('/user')
.post(function (req, res, next) {
    console.log(req.body);
    console.log(req.headers);
    //console.log(JSON.parse(Object.keys(req.body)[0]));
    res.json({title: 'RESTful: POST...'});
});

我打印了標題:但是req.body是空的,我使用了JSON.parse(Object.keys(req.body)[0])來解析其他類似問題的結果,但它對我不起作用。 我使用郵遞員來請求POST,

{ 'cache-control': 'no-cache',
'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/6.4.1',
accept: '*/*',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }

郵差截圖

您的路線似乎配置正確。 通過嘗試使用curl發出相同的請求,我將排除與郵遞員有趣的業務。

curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user

那么會發生什么?

編輯:從我在評論中收集的內容來看,您發布的請求看起來像是一個Content-Type: application/x-www-form-urlencoded標頭,但是有一個JSON正文{"name":"user"} 換句話說, 內容類型標題和正文不匹配

由於服務器期望URL編碼內容,因此無法解析請求正文。 因此,使Content-Type標頭與body格式一致非常重要。 所以在這種情況下,你有兩個選擇。

  1. 保留Content-Type: application/x-www-form-urlencoded並將正文更改為name=user
  2. 相應地將標題更改為Content-Type: application/json並將正文保留為{"name":"user"}

試試這個包。 傳遞表單數據時非常有用,而不是json格式。

https://www.npmjs.com/package/formidable

暫無
暫無

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

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