req.body undefined on server side

社会主义新天地 提交于 2019-12-23 09:26:30

问题


I am working on app which uses node, express, mysql on server side. i have written serveral APIs on server.js file and when i am trying to access those using Postman then req.body is always undefined.

this is my server.js configuration.

var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var bodyParser = require('body-parser');
var wrench = require("wrench");
var fs = require('fs');
var path = require("path");
var mkdirp = require('mkdirp');
var walk = require('walk');
var fse = require('fs-extra');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var crypto = require('crypto');

app.use(cors());

app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'pass',
    database: 'dbname'
});


connection.connect(function(err) {
    if (!err) {
        console.log("Database is connected ... \n\n");
    } else {
        console.log("Error connecting database ... \n\n");
    }
});

app.post('/urlreq', function(req, res){
    console.log(req.body);
}
app.listen(3000, function(){
    console.log("Rest Demo Listening on port 3000");
});

When i am trying send something in body in Postman then req.body is coming empty on server side.


回答1:


If you are sending multipart/form-data, it doesn't work because bodyparser doesn't handle this body type.

In this case adding the following line should fix it:

app.use(multipartMiddleware);

Form the docs:

multipart/form-data is the default encoding a web form uses to transfer data




回答2:


Try add:

var express = require('express');
var app = express();
[...]

// Last stack
app.listen(3000, function(){ 
    console.log("Rest Demo Listening on port 3000"); 
});



回答3:


You can use as a middleware also. Also listen on a port. add following lines in your code -

var app = express();

app.use(function(req, res, next) {      
  console.log('Current User:', req.body);
  next();
});

app.post('/url', function(req,res){
    console.log(req.body)
});


app.listen(3000, function(){
   console.log('Express server listening on port 3000');
});


来源:https://stackoverflow.com/questions/32630614/req-body-undefined-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!