使用Ajax从Node.js服务器获取JSON信息

3

我正在尝试使用ajax调用我的node js服务器,并将json正文返回给客户端。

以下是我的ajax调用代码。

self.information = function() {
      $.ajax({
          type: 'GET',
          url: 'http://localhost:3000/getIOT',
          contentType: 'application/json; charset=utf-8'
      })
      .done(function(result) {
        console.log(result);
      })
      .fail(function(xhr, status, error) {
          console.log(error);
      })
      .always(function(data){
      });
  }
}

以下是 Node.js 代码示例。

app.get('/getIOT', function (req, res , err) {
            request({
            'auth': {
                'user': 'masnad',
                'pass': 'whatstodaysrate',
                'sendImmediately': true
            },
            url: 'https://get.com/getAuroraRate?Amount=1000',
            method: 'GET',
        }, function (error, request, body) {
            console.log(body);
            return response.end(JSON.stringify(body));
        })
});

我遇到的错误是net::ERR_CONNECTION_REFUSED,而且响应体没有返回到ajax调用中。
/Users/nihit/Documents/node/multiple-js/server/server.js:36
            return response.end(JSON.stringify(body));
                   ^

ReferenceError: response is not defined
    at Request._callback (/Users/nihit/Documents/node/multiple-js/server/server.js:36:20)
    at Request.self.callback (/Users/nihit/Documents/node/multiple-js/node_modules/request/request.js:186:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:192:7)
    at Request.<anonymous> (/Users/nihit/Documents/node/multiple-js/node_modules/request/request.js:1081:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:189:7)
    at IncomingMessage.<anonymous> (/Users/nihit/Documents/node/multiple-js/node_modules/request/request.js:1001:12)
    at Object.onceWrapper (events.js:291:19)
    at emitNone (events.js:91:20)

我不确定我做错了什么。


需要更多的细节。您是否在控制台中看到类似于以下内容:Origin 'servername' is not allowed by Access-Control-Allow-Origin. - Colm Seale
@ColmSeale 等等,我遇到了错误,正在发布它们。 - Masnad Nihit
1个回答

2
您有一个错别字:response 应该是 res
app.get('/getIOT', function (req, res , err) { // <-- response is 'res'
        request({
        'auth': {
            'user': 'masnad',
            'pass': 'whatstodaysrate',
            'sendImmediately': true
        },
        url: 'https://get.com/getAuroraRate?Amount=1000',
        method: 'GET',
    }, function (error, request, body) {
        console.log(body);
        return res.end(JSON.stringify(body)); // <-- res
    })
});

补充:

根据您下面的评论,以下是可以对您的请求进行的一些清理工作:

$.ajax({
    type: 'GET',
    url: 'http://localhost:3000/getIOT',
    dataType: 'json',                              // <-- add this
    contentType: 'application/json; charset=utf-8' // <-- remove this
})
.done(function(result) {
    console.log(result);
})
.fail(function(xhr, status, error) {
    console.log(error);
})
.always(function(data){
});

说明:

  • dataType 告诉 jQuery 把返回的数据解析成 JSON 格式。
  • contentType 告诉服务器你发送的数据是 JSON 格式,但由于没有发送有效负载,所以在 GET 请求中不需要此参数。

顺便说一下,当我将数据返回时,它以这种格式传递给ajax:{"1":{"instalmentnbr":1,"duedate":"2017-03-27","currency":"1","capital_payment":"166.60"等等,有没有办法将它们作为JSON对象获取?谢谢! - Masnad Nihit
很简单,只需在您的Ajax请求中添加"dataType: 'json'"即可。 - technophobia
应该将 "res.end(JSON.stringify(body))" 更改为 "res.json(body);"。 - MTroy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接