首页 > 解决方案 > 使用 ajax 向 nodejs 发送 post 请求

问题描述

我正在尝试使用 ajax 向 nodeJS 发送数据:

var express = require('express');
var app = express();
var path = require('path')
app.use(express.urlencoded())
const router = express.Router();

router.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/client.html'));
  //__dirname : It will resolve to your project folder.
});


//add the router
app.use('/', router);

app.post('/endpoint', function(req, res){

    var obj = {};
    console.log('body: ' + JSON.stringify(req.body.title));
    res.send(req.body);
});
app.listen(3000);

应用程序.js

    <html>
    <head>
        <title>jsonp test</title>
        <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>      
        <script type="text/javascript">
            $(function(){               
                $('#select_link').click(function(e){
                    e.preventDefault();
                    console.log('select_link clicked');
                    var data = {};
                    data.title = "title";
                    data.message = "message";
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify(data),
                        contentType: 'application/json',
                        url: 'http://localhost:3000/endpoint',                      
                        success: function(data) {
                            console.log('success');
                            console.log(JSON.stringify(data));
                        }
                    });

                });             
            });
        </script>
    </head>
    <body>
        <div id="select_div"><a href="#" id="select_link">Test</a></div>    
    </body>
</html>

我不明白为什么我没有在服务器端接收数据,有人提示我该怎么做?

提前致谢 !

标签: node.jsajax

解决方案


发送data没有stringify

$.ajax({
  type: 'POST',
  data: data,
  contentType: 'application/json',
  url: 'http://localhost:3000/endpoint',
  success: function (data) {
    console.log('success');
    console.log(JSON.stringify(data));
  }
});

data.title您将可以访问req.body.title

app.post('/endpoint', function (req, res) {
  console.log('body: ' + req.body.title);
  //...
});

推荐阅读