【问题标题】:not able to send response from nodejs and capture it in jquery无法从 nodejs 发送响应并在 jquery 中捕获它
【发布时间】:2014-05-17 13:38:58
【问题描述】:

我正在尝试从 nodejs 函数发送消息作为响应,然后希望它通过 ajax jquery 捕获并将其打印在客户端 ID 上,但我总是收到 Error [Object object]。 这是我的代码 sn-p\

Server.js router.post('/checkUser', function(req, res) {

console.log("checking user");
var db=req.db;
var collection=db.get('userNameCollection');
    console.log("going to execute query:"+req.body.userName);
    collection.find({"user":req.body.userName},{},function(e,list)
    {
        if(list.length==1)
        {
            console.log("user name not available");
            res.writeHeader(200, {"Content-Type": "application/json"}); 
            res.send({data:"user name not available"});

        }
        else{
            console.log("user name available");
            res.writeHeader(200, {"Content-Type": "application/json"}); 
            res.send({data:"user name available"});
        }
        if (e) 
        {
            console.log("error: "+e);
        }
    });

});

index.jade

var myFunction=function(){
                var user = prompt("Please enter your name","User1");
                var url = 'http://localhost:8123/checkUser';
                var message = {userName: user};
                var dataType = 'json';
                $.ajax({
                    type: 'POST',
                    'url': url,
                    'data': message,
                    'dataType': dataType,
                    'success': function(data){
                        alert("Data:"+data.data);
                        console.log("data:"+data);
                    },
                    'error': function(error){
                        console.log('Error: ' + error);
                        alert("ERROR:"+error);
                    }
                })
            }

我无法弄清楚我在哪里做错了

【问题讨论】:

    标签: jquery ajax node.js express response


    【解决方案1】:

    我得到了解决方案,以供其他人将来参考。所以主要问题是跨域策略阻止数据交换。为了克服它,我只是将我的 jquery 移动到$('#testButton').click(function(){}) 所以这里是代码 sn-p

    index.jade

    extends layout
    
    block content
        body
            head
                script(src=' https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
    
        h1= title
        p Welcome to #{title}
        button(id='testButton') Test Button
        br
        h2#results
    script.
    $('#testButton').click(function(){
                    var message = {userName: "Pulkit Sharva"};
                    var dataType = 'application/json';
                    $.ajax({
                        url: '/checkUser1',
                        data: message,
                        type: 'POST',
                        dataType: 'json',
                        success: function (data) {
                            var ret = JSON.stringify(data);
                            console.log('Success: '+JSON.stringify(data))
                        },
                        error: function (xhr, status, error) {
                            console.log('Error: ' + JSON.stringify(error));
                        },
                    });
                });
    

    index.js

    router.post('/checkUser1', function(req, res) {
    console.log("From request:"+JSON.stringify(req.body));
    res.header("Access-Control-Allow-Origin", "*");
    res.send({'data': req.body.userName+' awesome'});
    

    });

    【讨论】:

      【解决方案2】:

      在服务器端试试这个:

      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,    Accept");
      res.json({"data":'all good'},200);
      

      这在客户端:

      $.ajax({
          type: "POST",
          url: "http://localhost:8123/checkUser",
          data:JSON.stringify({"g":"jh"}),
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(data){ console.log(data.data);
          },
          failure: function(errMsg) {
              console.log(errMsg);
          }
      });
      

      希望这能解决您的问题

      【讨论】:

      • 还是不行,如果有示例代码可以分享一下吗?
      猜你喜欢
      • 2021-08-21
      • 2020-01-31
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2017-12-21
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多