使用node.js和express进行JQuery Ajax post请求

11

我想使用JQuery向我的Node.JS和Express服务器发出AJAX POST请求,但它不起作用了!

var express = require('express')
var app = express();
app.listen(8888);

app.configure(function(){

   app.use(express.bodyParser());
   app.set('views',__dirname + '/views');
   app.set('view engine', 'ejs');
   app.use(express.static(__dirname + '/public'));
   app.use(express.cookieParser());
   app.use(app.router);

});

app.get('/', function (req, res){

   res.render('ajax.ejs');

});

app.post('/ajax', express.bodyParser(), function (req, res){

   console.log(req);
   console.log('req received');
   res.redirect('/');

});

这是ajax.ejs文件的内容:

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>    
  <script type="text/javascript">

      $('#enter').click(function(){  

     $.ajax({ 
           url: '/ajax',
           type: 'POST',
           cache: false, 
           data: { field1: 1, field2: 2 }, 
           success: function(data){
              alert('Success!')
           }
           , error: function(jqXHR, textStatus, err){
               alert('text status '+textStatus+', err '+err)
           }
        })
     });            

</script>
</head>
<body>

<form>
   <input type="button" id="enter" value="Enter">
</form>

</body> 
</html>

当加载ajax.ejs时,控制台中没有任何输出,因此,POST请求未能成功。我该怎么办?

提前感谢!


将express.bodyParser()移动到app.use()部分:app.use(express.bodyParser()); 你可以通过req.body检索post的主体。 - asgoth
完成了!所以我把 console.log(req); 改成了 console.log(req.body);。但是这个 post 请求仍然没有工作,控制台没有任何输出。 - MrMangado
2个回答

7
我发现了您的问题。您需要将您的脚本从头部移到主体部分(表单标签之后):
...
</form>
<script type="text/javascript">

   $('#enter').click(function(){  
   ...

</script>
</body>

6
以下代码按照新版本工作。 server.js
var express = require('express')
var app = express();
var bodyparser = require('body-parser');
var urlencodedparser = bodyparser.urlencoded({extended:false})

app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());

app.get('/', function (req, res){
   res.render('ajax.ejs');
});

app.post('/ajax', urlencodedparser, function (req, res){  
   console.log(req);
   console.log('req received');
   res.redirect('/');

});

app.listen(8888);

ajax.ejs

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>    

</head>
<body>

<form>
   <input type="button" id="enter" value="Enter">
     <script type="text/javascript">

      $('#enter').click(function(){  

     $.ajax({ 
           url: '/ajax',
           type: 'POST',
           cache: false, 
           data: { field1: 1, field2: 2 }, 
           success: function(data){
              alert('Success!')
           }
           , error: function(jqXHR, textStatus, err){
               alert('text status '+textStatus+', err '+err)
           }
        })
     });            

</script>
</form>

</body> 
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接