即時通訊嘗試獲取表單提交一些數據到我的快遞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)顯示什麼? –