使用ajax向postjs发送发布请求

时间:2019-09-23 15:13:52

标签: node.js ajax

我正在尝试使用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);

app.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>

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

提前谢谢!

1 个答案:

答案 0 :(得分:0)

发送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);
  //...
});