2017-05-12 121 views
1

聲明:快遞路由器後功能不能正常工作

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

Route.js:郵來電來訪

router.route('/signup') 
    .post(function (req, res) { 
     console.log('post signup called', req.body); 
     res.json({message: 'signup'}); 
    }); 

module.exports = router; 

req.body永遠是不確定的。我能夠在ajax調用中打印它們的控制檯。我不明白req.body是未定義的。我錯過了什麼?

阿賈克斯後的數據發送,如:

$.ajax({ 
    url: '/signup', 
    type: 'POST', 
    data: params, 
    success: function (res) { 
     console.log('res', res); 
    }, 
    error: function (err) { 
     console.log('err', err); 
    } 
}); 

服務器JS:已經使用body-parser這裏

var express = require("express"); 
var path = require('path'); 
var app = express(); 
var mongoose = require('mongoose'); 
var request = require("request"); 
var router = require('./app/routes/route.js'); 
var functions = require('./app/functions/functions.js'); 
var http = require('http'); 
var https = require('https'); 
var bodyParser = require('body-parser'); 
var nodemailer = require('nodemailer'); 
var model = require('./app/model/model.js'); 

app.use('/', express.static(__dirname + '/public_html')); 
app.use('/', router); 
app.use(bodyParser.json({limit: '5mb'})); 
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false })); 
+3

你需要使用['body-parser'](https://github.com/expressjs/body-p arser)在你的Express服務器上。 – robertklep

+0

@robertklep我已經在使用body parser – kittu

+0

@robertklep這樣做也是如此 – kittu

回答

5

您的申請將不予因爲你後宣佈它通過body-parser通過路由器(Express)按照聲明的順序通過中間件和路由傳遞請求;如果請求可以由router處理,則不會通過body-parser中間件了):

app.use('/', express.static(__dirname + '/public_html')); 
app.use('/', router); 
app.use(bodyParser.json({limit: '5mb'})); 
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false })); 

如果移動body-parser到前面,它應該更好的工作:

app.use('/', express.static(__dirname + '/public_html')); 
app.use(bodyParser.json({limit: '5mb'})); 
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false })); 
app.use('/', router); 
+0

謝謝。沒有意識到這一點。 – kittu