即时通讯尝试获取表单提交一些数据到我的快递app.js没有页面重新加载。我以为我有正确的代码,但当涉及到从ajax调用到服务器的代码,我得到一个未定义的数据变量。jquery ajax发布表达服务器获取未定义的数据
app.js:(去除不相关的线)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/web_text.json',function(req, res, next){
res.sendFile(__dirname + '/web_text.json');
});
app.post('/sendEmail', function (req, res) {
console.log(req.body.data);
});
app.use('/', index);
module.exports = app;
jQuery的功能,使得AJAX调用:
$('#reserve form').on('submit', function(){
event.preventDefault();
var data = {
name: $('#name').val()
};
console.log(data);
$.ajax({
url: 'http://localhost:3000/sendEmail',
data: data,
method: 'POST'
}).then(function (response) {
// Do stuff with the response, like add it to the page dynamically.
$('body').append(response);
}).catch(function (err){
console.error(err);
});
});
注意的console.log()在我的/ sendEmail app.post功能和jquery函数中的一个。 jQuery的人记录正确的数据,而app.post一个日志未定义的变量...我做错了什么?在此先感谢
isnt console.log(res.body.data)而不是console.log(req.body.data); – user1428716
nope ...使情况变得更糟,req.body.data导致未定义的数据变量,而res.body.data立即产生500错误代码 – cjlogrono11
console.log(req.body)显示什么? –