使用Node.js发布请求内容

时间:2017-06-03 11:35:47

标签: node.js express

我尝试将路由从Express App移动到另一个文件,但是当我尝试获取post请求的主体时,它是未定义的。

这是server.js文件:

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {colorize: true});
winston.add(winston.transports.File, { filename: 'server.err', level: 'error'});
winston.info('Starting server.');

var Firebase = require('firebase-admin');
var connection = require('./connection/firebaseConnection.json');

var express = require('express')
app = express();
var router = require('./srcs/router');
var bodyParser = require('body-parser');

try {
  Firebase.initializeApp({
    credential: Firebase.credential.cert({
      projectId: connection.firebase.project_id,
      clientEmail: connection.firebase.client_email,
      privateKey: connection.firebase.private_key
    }),
    databaseURL: 'https://' + connection.firebase.project_id + '.firebaseio.com'
  });
  winston.info('Connected to Firebase.');
} catch (error) {
  winston.error('Could not connect to Firebase : ' + error.code + ' : ' + error.message);
  process.exit(1);
}

app.use('/', router);

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

app.use(function(req, res, next) {
  var origin = req.headers.origin;
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST', 'GET');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  res.setHeader('Access-Control-Allow-Credentials', true);
  return next();
});

var server = app.listen(80, function() {
  winston.info('Server listening on port 80.');
});

这是router.js

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

var winston = require('winston');

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

module.exports = router;

我使用此命令对其进行了卷曲:

curl --data "title=test" http://localhost/post

并触发router.post但该值未定义。

1 个答案:

答案 0 :(得分:1)

尝试在路由器中间件调用之前添加bodyParser中间件(app.use调用)。

中间件按照添加顺序运行。您希望在到达路由器之前执行bodyParser

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

app.use('/', router);