使用ExpressJS,POST请求为空

时间:2016-03-15 21:11:02

标签: javascript node.js express

当我对我的服务器路由发出POST请求时,request.body为空。我使用正文解析器来获取JSON数据。我做错了什么?

_saveTicket函数上,我有console.log来显示所有正文请求参数。当我发出POST请求时,request.body为空。

我需要自动解析它吗?

server.js

/**
 * Declaration
 **/
var     express   = require('express'),
        database  = require('./config/database.js'),
        morgan    = require('morgan'),
        port      = 2559,
        bodyPar   = require('body-parser'),
        methodOv  = require('method-override'),
        mongoose  = require('mongoose'),
        fsr       = require('file-stream-rotator'),
        logDirectory = __dirname + '/log',
        favicon   = require ('serve-favicon');
        app       = express();

/**
 * DB Connection
 **/
mongoose.connect(database.mongo);

/**
 * Api definition
 **/
 var accessLogStream = fsr.getStream({
   date_format: 'YYYYMMDD',
   filename: logDirectory + '/access-%DATE%.log',
   frequency: 'daily',
   verbose: false
 })

app.use(express.static(__dirname + '/public'));
app.use(morgan('combined', {stream: accessLogStream}));
app.use(bodyPar.urlencoded({'extended':'true'}));
app.use(bodyPar.json());
app.use(bodyPar.json({ type: 'application/vnd.api+json' }));
app.use(methodOv('X-HTTP-Method-Override'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));

/**
 * Routes section
 **/
require('./routes/ticket.js')(app);

/**
 * Starting server
 **/
app.listen (port)
console.log ("Listening on port: " + port);

模型/ ticket.js

var mongoose = require('mongoose');

var TicketSchema = new mongoose.Schema({
  title:          String,
  description:    String
}, {versionKey: false});

module.exports = mongoose.model('Ticket', TicketSchema, 'Ticket');

路由/ ticket.js

var Ticket = require('../models/ticket');

module.exports = function(app){

   _getAllTickets = function(req, res){
    var query = Ticket.find().lean();

    query.exec(function(err, lst){
      if(err)
        res.send(err);

      res.json(lst);
    });
  };

  _saveTicket = function(req, res){
    console.log(req.body);

    var tckt = new Ticket({
      title: req.body.title,
      description: req.body.description
    });

    tckt.save(function(err){
      if(!err)
        console.log('Ticket creation successful. ');
      else
        console.log('ERROR: ' + err);
    });

    res.send(tckt);
  };

  app.get('/api/tickets/', _getAllTickets);
  app.post('/api/tickets/', _saveTicket);
}

1 个答案:

答案 0 :(得分:1)

根据您的<?php $icons = array( 'fugue' => array( 'home' => 'hello', ), ); ?> <?php $icons = array( 'silk' => array( 'home' => 'hellosies', ), ); ?> 中间件定义,确保HTTP请求的Content-Type标头设置为application/jsonx-www-form-urlencoded。我的猜测是它现在正好是body-parser