I have code snippet where I am pulling all the configs from back-end Node server through $.ajax
. But when I hit My page first time, I do not get the response, where as When I check the log on node server, I do see the status for the request as 200 Ok. But I refresh the page twice or thrice I get the response properly.
Below is my code:
var appConfig = getConfig();
function setAppConfig(){
var url = env.NEW_SERVER_URL + '/api/client/getConfig/carrier/';
$.ajax({
type: 'GET',
contentType: "application/json",
url: url,
success: function (response) {
// console.log(response);
var configData = JSON.stringify(response);
sessionStorage.setItem('config', configData);
return true;
},
error: function (error) {
console.log("some error in connection with server");
return false;
}
});
}
function getConfig(){
var appConfig = "";
// console.log(fetchFromSession('config'));
if(fetchFromSession('config') !== null){
appConfig = JSON.parse(fetchFromSession('config'));
}else{
if(setAppConfig()){
appConfig = JSON.parse(fetchFromSession('config'));
}else{
console.log('Something went wrong in pullling the configs');
}
}
return appConfig;
}
Node Server Code to respond the get request:
exports.config = ((req, res,next) => {
let carrier = req.params.carrier;
logger.info("getConfig started", {carrier: carrier});
if(carrier){
var msg = require(path.join('./../../../config/',carrier,'/config.json'));
logger.info("Response for getScripts", {carrier: carrier, response: msg});
res.send(msg);
}
})
This script is loaded first on the page and all the dependent scripts are marked defer
to wait for it to get loaded
Questions:
- What is wrong with my code?
- Why does it doesnt work first time but works on refreshing the page after that?
- what do I need to do to get the successful response on first load itself?