使用ajax从js服务器获取json信息
我试着让ajax调用我的节点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){ }); } }
这里是节点的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)
不知道我在做什么错。
你有一个错字: 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将返回的数据parsing为JSON。 -
contentType
告诉服务器你发送的数据是JSON,但你没有发送一个有效载荷,所以你不需要这个GET请求。