如何在app.post中获得post params

时间:2015-06-11 13:14:58

标签: node.js express ejs

我正在开发nodejs项目。我在express-helpers模块的帮助下使用ejs来生成视图模板html。

function downloadXLS() { var AUTH_TOKEN = "xxxx"; var auth = "AuthSub token=\"" + AUTH_TOKEN + "\""; var file = Drive.Files.get('xxxx'); var response = UrlFetchApp.fetch('https://docs.google.com/spreadsheets/d/xxx/export?format=xlsx',{headers: {Authorization: auth}}); var doc = response.getBlob(); app = DriveApp.createFile(doc).setName(file.title + '.xls') MailApp.sendEmail("xxx@xxx.com", "oh man", " Body", { attachments: app }) } 文件中我写了以下代码

server.js

我想知道var http = require('http'); var path = require('path'); var async = require('async'); var socketio = require('socket.io'); var express = require('express'); var app = express(); var helpers = require('express-helpers') helpers(app); var server = http.Server(app); server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){ var addr = server.address(); console.log("Chat server listening at", addr.address + ":" + addr.port); }); app.use(express.static(__dirname + '/public')); app.set('views', __dirname + '/public/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); //app.use(express.static(__dirname + '/client')); app.use(express.static(path.join(__dirname, '/client'))); // respond with "index.html" when a GET request is made to the homepage app.get('/', function(req, res) { res.render('index.html'); }); app.get('/demo', function (req, res) { res.render('demo.ejs'); }); app.post('/demo', function (req, res) { console.log(res.body) }); 我应该如何获得post params

app.post

我尝试了app.post('/demo', function (req, res) { console.log(res.body) }); ,但是给了console.log(req.body) 还尝试了undefined,但提供了console.log(res.body)

请告诉我应该如何实施?

2 个答案:

答案 0 :(得分:4)

您应该使用body-parser

等中间件
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

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

答案 1 :(得分:2)

使用body-parser中间件。首先,您需要使用npm install body-parser安装它。然后在你的应用程序中使用它

var bodyParser = require('body-parser');
.....

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

....

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