0

I've created a very basic express js application. After setting routes and other things I did app.use('/api/', require('./api/api.js'));

api.js looks something like this:

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

router.post('/', function(req, res){
      res.end(req.body);
});

module.exports = router;

I'm using Postman chrome extension to post to this route. The response is empty {}.

The question is: as long as I have in my app.js body-parser middleware set do I need to set it again in api.js ? If not why I have an empty response ?

In app.js body-parser is set like this:

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

2 回答 2

1

尝试这个

应用程序.js

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

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

var api = require('./api');
app.use('/api', api);


var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

api.js

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

router.post('/', function (req, res) {
  res.send((req.body);
});

module.exports = router

然后,在您的 PostMan 请求中,类似于:

在此处输入图像描述

于 2015-04-17T08:21:01.407 回答
0

你曾经使用/api/app.use('/api/', require('./api/api.js'));的路线和你使用过的路线router.post('/', ...。如果您删除其中的尾部正斜杠,/api/它可能会起作用。

于 2020-07-07T08:15:43.107 回答