[英]Casperjs, how to only proceed after receiving response from an ajax call
[英]AJAX call not receiving a response from webserver
我看過相關的問題,沒有一個對我有幫助。 因此,我正在提出這個問題。
因此,我的客戶端解密URL並將其發送到我的服務器,然后由我的服務器解密並使用解密后的請求進行API調用。 在服務器端,一切似乎工作正常。 沒有錯誤被拋出。 日志似乎很好,等等。
我的AJAX看起來像:
var handleRequest = function(request){
$.ajax({
type: "GET",
url: host + '/requests?call=' + request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
console.log('Recieved: ' + rawJSON);
editor.setValue(rawJSON);
},
error: function(jqXHR, responseText,status){
console.log(jqXHR.responseText)
},
dataType: 'jsonp'
});
}
服務器端:
app.get('/requests', function(req, res) {
var call = req.query.call;
var decryptedRequest = decryptRequest(call);
console.log("Recieved: " + decryptedRequest);
var rawJson = retriever.makeExternalCall(decryptedRequest);
console.log('Sending response to client');
res.setHeader('Content-Type', 'application/json');
res.send(rawJson);
});
上面使用的方法:
var requestService = require('request');
module.exports = {
makeExternalCall: function(url) {
console.log('Making call to: ' + url);
requestService(url, function(error, response, body){
console.log(body);
return body;
});
}
}
奇怪的是當我更換
res.send(rawJson);
與
res.send('hello');
我得到回應。 對這里發生的事情有什么想法嗎?
函數makeExternalCall
是一個異步函數。 從回調返回不起作用,因為異步函數在返回數據之前已經返回,因此is undefined
rawJson
。
解決方案是正確使用回調。
var requestService = require('request');
module.exports = {
makeExternalCall: function(url,callback) {
console.log('Making call to: ' + url);
requestService(url, callback);
}
}
然后在API處理程序中
app.get('/requests', function(req, res) {
var call = req.query.call;
var decryptedRequest = decryptRequest(call);
console.log("Recieved: " + decryptedRequest);
retriever.makeExternalCall(decryptedRequest, function(error, response, body) {
if (error) {
res.send("error message");
} else {
res.setHeader('Content-Type', 'application/json');
res.send(body);
}
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.