【问题标题】:JQuery Ajax Post cannot send data (json) to express.js serverJQuery Ajax Post 无法将数据(json)发送到 express.js 服务器
【发布时间】:2015-06-11 10:36:17
【问题描述】:

我是 Node.js 的新手。我在这里要做的是以json格式发送一些数据,从客户端javascript到express.js服务器。一旦我能做到这一点,我将使用那些已发送到服务器的参数来进一步从 MongoDB 检索信息。客户端代码真的很简单,有一个点击事件:

 $.ajax({
                url: 'http://localhost:8020/1',
                type: 'post',
                dataType: 'jsonp',
                data: JSON.stringify({name: "test"}),
                contentType: 'application/json',
                success: function(data){
                alert("success");
                alert(data);
            }
    });

在服务器端,代码如下所示:

    var express = require('express');
    var app = express();
    var cons = require('consolidate'),
        MongoClient = require('mongodb').MongoClient,
        Server = require('mongodb').Server; 

    var mongoclient = new MongoClient (new Server('localhost', 27017,
                            {'native_parser' : true}));
    var db=mongoclient.db('test');

    var bodyParser = require('body-parser');

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));


    app.all('/*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      next();
     });

    app.get('/1', function (req, res) {
        db.collection('test').findOne({}, function (err, doc){
           console.log(doc);
        });
        console.log(JSON.stringify(req.body));
        var x = req.body.name;
        console.log(x);
        res.send({});
    });


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

           db.collection('test').findOne({}, function (err, doc){
               console.log(doc);
            });

           console.log(req.body);
    });

    mongoclient.open(function (err, mongoclient) {

        if (err) throw err;
        app.listen(8020);
        console.log("listening on port 8020");
    });

当我进行客户端 ajax 调用时,似乎服务器端代码成功返回了我的 mongoDB 数据库中的一个项目,但它未能捕获数据,在这种情况下为 {name : "test"}。以下是触发点击事件时服务器端控制台的输出:

{}
undefined
{ _id: 5522f3368d21ba45c6263402, apple: 'juice' }

有人对此有任何想法吗?这与跨域问题有关吗?非常感谢!

【问题讨论】:

  • 提供的信息不足以成为一个正确的问题。建议学习一些ajax教程,然后提供更具体的代码相关问题
  • 无法使用 jsonp 数据类型进行 POST。

标签: jquery ajax node.js mongodb jsonp


【解决方案1】:
  1. 您正在发送 jsonp 作为您的数据类型。我猜 jQuery 会执行一些魔法来为您创建 jsonp 请求。你确定你需要这样做吗?

  2. 您没有从您的 POST 路由响应。这将使请求无限期挂起。你必须回应:

    app.post('/1', function (req, res){
    
           db.collection('test').findOne({}, function (err, doc){
               console.log(doc);
               res.send(doc); // respond!
           });
    
           console.log(req.body);
    });
    

【讨论】:

    【解决方案2】:

    首先将数据作为 JSON 而不是字符串发送

     $.ajax({
                url: '/1',
                type: 'post',
                dataType: 'json',
                data: {name: "test"},
                contentType: 'application/json',
                success: function(data){
                   alert("success");
                   alert(data);
            }
    });
    

    在服务器上

    app.post('/1', function(req, res) {
      var body = req.body;
    
      console.log(body)
      res.send(body)
    });
    

    【讨论】:

    • 感谢您的回答。但是,如果我将 url 格式化为“/1”,我会收到“加载资源失败:服务器响应状态为 404(未找到)”的错误消息。我在想是否是因为我的 Windows PC 上没有安装真正的网络服务器,而谷歌浏览器通过这个 url 将我定向到本地文件位置。如果我在“/1”之前添加“localhost:8020”,我会遇到跨域问题。对此有任何想法吗?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2014-03-22
    相关资源
    最近更新 更多