3

I do not know why the req.body is EMPTY... app.js use the body-parser middleware(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...'});
});

I have printed the headers: But the req.body is empty and I used the JSON.parse(Object.keys(req.body)[0]) to parse the result from the other similar question, but it did not work to me. I use the postman to request the 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' }

postman screenshot

Joy
  • 31
  • 4

2 Answers2

2

Your routes seem to be configured correctly. I'd rule out any funny business with postman by trying to make the same request using curl.

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

What happens then?

EDIT: From what I gather in the comments, it looks like the request you were posting contained a Content-Type: application/x-www-form-urlencoded header, but with a JSON body {"name":"user"}. In other words, the content-type header and the body are mismatched.

Because the server was expecting URL encoded content, it would have been unable to parse the request body. For that reason, it's important to make the Content-Type header agree with body format. So in this case, you have two options.

  1. Keep Content-Type: application/x-www-form-urlencoded and change the body to name=user
  2. Change your header accordingly to Content-Type: application/json and keep the body as {"name":"user"}
  • Hi An Camchéachta, if I change to application/json and the raw data is { "name": "user"}, I can get the json data from req.body, but why x-www-form-urlencoded can't ?? – Joy Nov 16 '17 at 14:19
  • `{ 'cache-control': 'no-cache', 'postman-token': '852df9bf-d4f2-481d-baab-f91b3354f16b', 'content-type': 'application/json', 'user-agent': 'PostmanRuntime/6.4.1', accept: '*/*',
    host: 'localhost:3000',
    'accept-encoding': 'gzip, deflate', 'content-length': '19', connection: 'keep-alive' } {"name":"user"}` <-- content of req.body
    – Joy Nov 16 '17 at 14:21
  • Hi Joy, Sure. Are you sending the body in question as a valid urlencoded string? In other words, is the body getting sent as: `name=user`? There's a great explanation for how to format your body as `application/x-www-form-urlencoded` [in this Mozilla doc](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST). Might you have been sending over a string of JSON instead of this? – An Camchéachta Nov 16 '17 at 15:06
  • Hi An Camchéachta, at the footer of my question, there is a screenshot of the postman which includes the data sent by application/x-www-form-urlencoded, I think the data format is right, as the data structure is provided by postman. – Joy Nov 17 '17 at 01:45
  • Hi @An Camchéachta **Keep Content-Type: application/x-www-form-urlencoded and change the body to name=user** this case is what I wanted, as the screenshot shown, but the result it is unexpected. – Joy Nov 17 '17 at 01:49
  • As I see from Google search results, postman lets you [inspect the raw body](https://www.getpostman.com/docs/postman/sending_api_requests/requests#raw). Maybe that will help you. – An Camchéachta Nov 17 '17 at 10:31
  • `{ 'cache-control': 'no-cache', 'postman-token': 'ab73ef15-3313-4cde-b687-85cf0397da0b', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'PostmanRuntime/6.4.1', accept: '*/*', host: 'localhost:3000', 'accept-encoding': 'gzip, deflate', 'content-length': '19', connection: 'keep-alive' }` {"{\n\t\"name\": \"user\"\n}":""} //the req.body when I choose the **text** raw data` in postman. But from the postman introduction: https://www.getpostman.com/docs/postman/sending_api_requests /requests, I can input form data as the screenshot.@An Camchéachta – Joy Nov 18 '17 at 04:08
  • CamchéachtaI created a view to test the post, it worked **{"user_name":"joy","age":"12","country":"China"}**. but I do not know why.
    – Joy Nov 18 '17 at 04:15
  • created a view to test the post, it worked **{"user_name":"joy","age":"12","country":"China"}**. but I do not know why.
    – Joy Nov 18 '17 at 04:20
0

Try this package. It is useful when you are passing form data and not in json format.

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

parth
  • 624
  • 1
  • 10
  • 29
  • Hi @parth, maybe this package is a good way to get form data not in json format. And I want to know why when I set the **Content-Type: application/x-www-form-urlencoded**, and the sent data format is right, but can't not receive the result by req.body? Could u help to explain it? – Joy Nov 17 '17 at 02:00
  • Explanation given on this link . https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data. Also when sending other then json data, look your headers. If it's set to Applocation/json then uncheck it. – parth Nov 17 '17 at 05:15