firefox addon main.js is showing same request response, not updating - javascript

What I'm doing wrong with addon builder? , it is not showing new request response, it show same response all the time, here is my code for main.js :
var tmr = require('timer');
var timus=5000;
var Request = require("sdk/request").Request;
function timer_restarting(){
gint = tmr.setInterval(function() {
Request({
url: "http://mysite.com/data.txt",
onComplete: function (response) {
if(response.text.indexOf('<show>true</show>')>-1){
timus = parseInt(response.text.substring(response.text.indexOf('<interval>')+10,response.text.indexOf('</interval>')));
show(response.text.substring(response.text.indexOf('<message>')+9,response.text.indexOf('</message>')));
tmr.clearInterval(gint);
timer_restarting();
}
}
}).get();
}, timus);
}
timer_restarting();
the addon show every 5 sec same message, it is not updating . I have an impression like it is not doing new request to server. I have changed message but it still show old message. what is the issue?
please
UPDATE:
if I will manually go to that link in browser and refresh it, then addon will refresh the respone as well. Why is that happening ?

Try adding a header for 'Cache-control' to your Request instance, and specify a value of 'no-cache' (or some 'max-age' value), to prevent getting a cached response.
E.g. in your example, between the lines
url: "http://mysite.com/data.txt",
onComplete: function (response) { /* ... */ }
insert the following lines:
url: "http://mysite.com/data.txt",
headers: {
'Cache-control': 'no-cache'
},
onComplete: function (response) { /* ... */ }

Related

Cookies not being sent on cross-sub-domain request on an api call

I have a page stored on https://page.domain.com.
Here, I'm using javascript (mainly Bootstrap) to get data from https://api.domain.com.
The first call, when the page is loaded, is a "sort of" authentication call which return a cookie in the headers:
set-cookie: oauth=emd4YWgybTJobmJnZjVrbXl2ZjdlZThiOzkzczg1YWt2YzNyZW42cjk3M2U4dXlweA==; domain=.domain.com; path=/; expires=Fri, 16 Apr 2021 11:58:07 GMT;
I can see in the developer tools (Chrome) that the cookie is stored correctly.
But then, when I make the next api call (example, filling a dropdown list - bootstrap autocomplete ) the cookie is not in the request.
This was working fine when I was building it in localhost (same "domain", I guess) but now, having the html and the apis running on different domains, it seems cookies are not being shared.
I thought it could be because of the two different domains, but according to the documentation, when a cookie is set to the main domain, all sub-domains should be able to share it. (also, I' including the "withCredentials" flag)
This is the code of the initial call (and setting up the subsequent one):
$.ajax({url: 'https://api.domain.com/get-cookie',
xhrFields: {
withCredentials: true
}
})
.done(function (response) {
$('.selectpicker').selectpicker().ajaxSelectPicker({
ajax: {
// data source
url: 'https://api.domain.com/data.json',
// ajax type
type: 'GET',
// data type
dataType: 'json',
// Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
// automatically replace it with the value of the search query.
data: {
q: '{{{q}}}'
}
},
// function to preprocess JSON data
preprocessData: function (data) {
var i, l = data.length, array = [];
if (l) {
for (i = 0; i < l; i++) {
array.push($.extend(true, data[i], {
text : data[i].name,
value: data[i].code,
data : {
subtext: data[i].code
}
}));
localStorage.setItem(data[i].code, data[i].name);
}
}
// You must always return a valid array when processing data. The
// data argument passed is a clone and cannot be modified directly.
return array;
}
});
}
);
I'm using AWS API Gateway and Lambda functions, but that should not be relevant...
When taking the url from the selectPicker (eg: https://api.domain.com/data.json ) and putting it directly in the browser I see the cookie being sent.
This seems to indicate the issue might be in the Bootstrap Select component that is not sending the headers correctly.
I'm not sure if I can make it work as expected or I have to find some other alternative.
The solution was to also include the withCredentials on the selector request:
$('.selectpicker').selectpicker().ajaxSelectPicker({
ajax: {
// data source
url: 'https://api.domain.com/data.json',
// ajax type
type: 'GET',
// data type
dataType: 'json',
// Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
// automatically replace it with the value of the search query.
data: {
q: '{{{q}}}'
},
xhrFields: {
withCredentials: true
}
},
// function to preprocess JSON data
preprocessData: function (data) {
// ...
}
});
}
);
Thanks #CBroe for the idea in the comments.

Ionic v1 AngularJS $http POST request not working

I'm trying to send a POST request to a rest API, but I don't seem to able to do it correctly, I don't know if it's the syntax, or what it could be, I've tried many different ways but nothing seems to work. Here's is some pictures of the service being consumed by POSTMAN (everything works fine here).
The Headers
And the body with the response
But then when I try to consume the service via AngularJS, it keeps sending me erros messages, the localhost server even detects that there is a request, because I can see it on the Eclipse's console, but it doesn't run through the debugger with togglebreakpoints and it does with POSTMAN.
This is one of the many attempts to send a $http request
var json = { practiceId: 1 };
$http({
method: "POST",
url: "https://localhost/GetAppointmentTypes",
data: JSON.stringify(json),
headers: {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
}
})
.success(function(data) {
$ionicPopup.alert({
title: 'WORKING'
});
})
.error(function (errResponse, status) {
if(status == 403){
$ionicPopup.alert({
title: '403'
});
}
});
But then
And here is another attempt
var url = 'https://localhost/GetAppointmentTypes';
var parameter = JSON.stringify({practiceId:1});
var headers = {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
};
$http.post(url, parameter, headers).then(function(response){
$ionicPopup.alert({
title: 'WORKING'
});
}, function(response){
$ionicPopup.alert({
title: ' NOT WORKING '
});
});
And the response
Note: the $window.localStorage['token'] is working correctly. I have tried so many things I don't even know what I'm doing wrong now, might be a syntax error, but then ERROR 403 wouldn't be showing.
EDITED (ADDED)
And the Response Variable

How to successfully use the callback on an javascript function with an http request

Note: I have limited exp with js so correct me if my I'm completely wrong in how I'm describing this scenario.
I have two javascript files. I am calling a function on the first file (client side) which calls a function on the second file and uses the callback from the second file's function for the purposes of response.success/.error on the first file.
If that doesn't make sense here is some code:
Note: this is being done temporarily using Parse's cloud functions. Let me know if more information is needed regarding those but not sure if it's important.
First file:
Parse.Cloud.define("methodName", function(request, response) {
...
secondFile.myFunction(param1, {
stuff: request.params.stuff,
}, function (err, res) {
if (err) {
response.error(err);
} else {
response.success(res);// I'm assuming this is going to the hardcoded "yes." from httpRequest on second file's function
}
});
});
Second File:
myFunction: function(param1, properties, callback) {
if (!param1) return callback(new Error("Helpful error message"));
var headersForReq = {
...
};
var bodyForReq = ...; // the properties properly parsed
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq,
success: function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
error: function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
}
On my the client, the code is treated as a success (errors aren't thrown or returned back) but when I print out the value it comes across as (null) not "yes".
What's going on here? (Side note, httpRequest is currently not doing anything, its hard to verify if the request is properly being sent because it's being sent to a third party API).
I do know the second file's method is properly being called though. So it's not a silly issue with the module.exports or var secondFile = require('\path\secondFile')
I think you are just mis-use the api
Rewrite it with the example style.
https://parse.com/docs/js/api/classes/Parse.Cloud.html#methods_httpRequest
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq
}).then(function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
I think below will work, too.
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq
}, {
success: function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
error: function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
BTW, if you are using open source parse-server, you can use request or request-promise. These 2 npm package is used by many people. (Parse.Promise is not es6-like promise)

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Sending 'Authorization' header in Ext JS Ajax Request, Chrome vs. Firefox

In code the request is sent as:
var ajaxOptions = {
url: 'someUrl',
method: 'POST',
success: function(response) {
...
},
failure: function(response) {
console.log(response);
}
};
var form = this.getView().getForm();
var submitAction = Ext.create('Ext.form.action.Submit', { form: form });
var formInfo = submitAction.buildForm();
ajaxOptions.form = formInfo.formEl;
if (form.hasUpload()) {
ajaxOptions.isUpload = true;
}
Ext.Ajax.request(ajaxOptions);
When a request is sent via Chrome, the 'Authorization' header presents:
Authorization:Basic YWRtaW46YWRtaW4=
When it is sent via Firefox, the header is not included.
Explicitely I don't set user/password. So it's not clear, why and how chrome sends such header. Are there any known issues?
The second, how to force firefox to send such header? Is it possible?
UPDATED
JavaScript does not now anything about login/password. The main question, how Chrome can use them, but other browsers cannot send such pair. So the question is how to force other browsers to send this cookie as Chrome does without appling headers manually via JavaScript.
On the server side, the Servlet API is used. in web.xml:
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>someName</realm-name>
</login-config>
if it does matter
Per the docs, just add a headers property to your ajaxOptions:
ajaxOptions = {
//...
headers : {
'Authorization': 'Basic YWRtaW46YWRtaW4='
}
}

Categories

Resources