【问题标题】:ajax GET call with node.js / express server使用 node.js / express 服务器的 ajax GET 调用
【发布时间】:2013-11-06 19:34:21
【问题描述】:

我正在尝试为 node.js 编写一个小的 ajax 实时搜索。首先是我的客户端代码:

  $('#words').bind('keyup', function(){
    getMatchingWords($('#words').val(), function (data){
      console.log('recieved data');
      console.log(data);
      $('#ajaxresults').show();
    });
  });

function getMatchingWords(value, callback) {
    $.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
        type: 'GET',
        dataType: 'json',
        success: function(data) { if ( callback ) callback(data); },
        error  : function()     { if ( callback ) callback(null); }
    });
}

这是我的服务器端路由:

app.get('/matchword/:value', function(req, res) {
      console.log(req.params.value);
      res.writeHead(200, {'content-type': 'text/json' });
      res.write( JSON.stringify({ test : 'test'}) );
      res.end('\n');
});

它有效,但我没有收到任何数据。回调函数中的数据始终为空。所以我做错了什么?谢谢你的帮助

【问题讨论】:

  • 不确定这是否对 node.js 有影响,但 content-type 不应该是 Content-Type

标签: ajax node.js express


【解决方案1】:

改变

$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {

$.ajax('/matchword' + value + '/', {

【讨论】:

    【解决方案2】:

    您发出 $.ajax() 请求的 URL 是什么?如果包含该客户端 JS 的页面也不是从 127.0.0.1:3000 加载的,那么您看到的错误是由于 AJAX 请求的同源要求。

    【讨论】:

      【解决方案3】:

      迟到总比没有好......

      我正在查看您的问题,因为我还尝试将简单的实时搜索与 express.js 后端放在一起。

      首先,我将您的网址放入一个局部变量中。因为我不认为那是你的问题。 特别是如果您的 express / node 日志显示 200 响应。然后网址就可以了...

      您的函数似乎没有返回数据(正确吗?)如果是这样试试这个。

      var search_url = "..."// your url
      
      function getMatchingWords(value, callback) {
          $.ajax(search_url, {
              type: 'GET',
              dataType: 'json',
              success: function (data, textStatus, jqXHR) {
                  var returned_data = data;
                  console.log("returned_data ="+returned_data);//comment out or remove this debug after test
                  callback(returned_data);
              },
              error: function( req, status, err ) {
                  console.log( 'something went wrong', status, err );
              }
          });
      }
      

      您可能还需要根据设置添加/修改标题...

              headers : { Authorization : auth },
              type: 'GET',
              dataType: 'json',  
              crossDomain:true,
      

      auth 变量是代码中其他位置的编码身份验证对(如果您的 Web 服务需要某种身份验证...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-20
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        • 2016-08-16
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多