Setting up CORS not working - javascript

I have the following headers set on the server
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.addHeader("Access-Control-Allow-Headers","X-Custom-Header");
And i want to use the POST method to access a web service and send data to it but the problem is my setting up with the server is causing problems
I used the following method
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Safari/Firefox.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
and based on this object
url = "http://myurl.do";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
return;
}
var params = "name=pari123&action=initaction&gameId=slotreel3";
xhr.setRequestHeader('Content-Type', 'application/text/plain');
if(xhr.readyState == 4 && xhr.status == 200)
{
alert('Tested OK')
xhr.send(params);
}
else
{
alert('status not 200 or xhr is not ready');
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
But always it alerts a message saying 'status not 200 or xhr is not ready' i am not able to proceed any one if you know please kindly help!
when i print the xhr.readyState its printing a value of 1

if(xhr.readyState == 4 && xhr.status == 200)
This check must be placed in the onreadystatechange event handler. You obviously cannot have a 200 status code or a "finished" request before actually sending it.
What you wanted is probably this:
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert('Tested OK');
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
}
};
xhr.send(params);
If you want an else case to check for errors remember that you still need to check for xhr.readyState == 4. You don't want your error-handling code to run for other readyStates.
There is no need for the onload event - when you get readyState == 4 you know the request has finished.

There can be several issues here.
I observed that different browsers implement CORS differently. My experience is based on Firefox and Google Chrome. For example, I had to add a special header on server side, so that Firefox would make the preflight (OPTIONS) request and the actual request (GET,PUT etc.) using one connection as Google Chrome does it. You would have to add on the server side:
response.addHeader("Keep-Alive", "timeout=2, max=100");
response.addHeader("Connection", "Keep-Alive");
I also noticed that some browsers do not like the wildcard ("*") in the CORS headers. A workaround for the line
response.addHeader("Access-Control-Allow-Origin", "*");
would be to return the origin of the request and not a wildcard.
However, there could be also other problems and we would need more details. For example, does the request work when the server is hosted on the same domain (i.e. the problem might not be related to CORS). What server are you using?

xhr.send(); needs to be just after the call to xhr.open(); does it not? Status 1 means the request has not been sent yet, it'll never get to status 4 unless you actually send the request..

Related

Check if POST was successful and then run JavaScript

How do I check, if a POST XHR request was successful, on a website, for a particular URL?
If the POST was successful, I then want to run some JavaScript.
I've seen ways to do this in jQuery, but I want to do this via vanilla JavaScript.
You can use the status code to check if the request was successful:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// successful
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
https://stackoverflow.com/a/3038972/10551293

Execute a http request response in javascript

I have an http request which delivers 'JSON.stringify(data)'.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/hello", true);
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
};
How can I run the code and print the contents of data?
your code should be working, the endpoint may be the problem, check the url your trying to get into the endpoint from, then don't forget to check the readyState and the status of your request before doing nothing.
xhr.onreadystatechange = function () {
if (xhr.readState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
}
};

Writing Request Payload property on httprequest

I am trying to develop a browser extension that will help people to some stuff way easier.
One of the things that I need to do is sending couple of http requests.
I need to recreate requests that site makes when doing certain things.
Now site uses Request Payload which is my first time using(used form data),therefore I don't know how to make Request Payload same as when site sends request.
var request = new XMLHttpRequest(),
url = 'https://www.hidden.com/api/v1/tipuser/',
data = 'steam_64=76561198364912967&tip_asset_ids=[]&tip_balance=0',
token ='...';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'text/plain');
request.setRequestHeader('authorization', token);
request.send(data);
This is my code and after sending it you can see how my Request Payload looks.
I have been having difficulties for days now and I searched online but couldn't find solution to this.I know that I just have to write it differently .
This is site's request
This is my request
Cheers!
Could you try sending your request as application/json and build your data object like in the example below?
Your Content-type request header should be application/json
var request = new XMLHttpRequest(),
url = 'https://jsonplaceholder.typicode.com/posts/',
data = {
steam_64: '76561198364912967',
tip_asset_ids: [],
tip_balance: 0,
token: '',
};
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('authorization', data.token);
request.send(JSON.stringify(data));

Ajax request in Chrome extension

I am developing an extenion which makes an ajax request to a web server like this
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 204)
{
//debugger;
alert("Logged in");
flag = 1;
_callBack(xhr, xhr.readyState);
}
}
And here i am able to logged in with status = 204 and now once i logged in i am trying to go for different directory for example www.example.com/index/enter with another ajax request in same extension but could not able to do so.
Are you sure you're expecting the same HTTP response code? It's very likely that the server you're making requests to is sending a different response for a different request URL.
204 No Reponse = there is no response data
200 OK = there is data

Handle specific 404 error and get responseText with XDomainRequest for IE

I am using CORS to make cross domain call. My problem here is I need to handle the 404 error in XDomainRequest in IE.
In XDomainRequest I can only find onerror event to handle all the error event, but in my requirement I need to show empty placeholder images for 404 error case (The API doesn't provide empty 200 response for this,but use 404) but regardless other errors.
This is the request URL:
http://photorankapi-a.akamaihd.net/streams/1537083805/media/photorank?auth_token=11ff75db4075b453ac4a21146a210e347479b26b67b1a396d9e29705150daa0d&version=v2.1
In other browsers, I use XMLHttpRequest and req.status code == 404 to get the responseText:
{"metadata":{"code":404,"message":"Not Found","version":"v2.1"}}
But When I tried to get the responseText from req.onerror(below), I can get empty string only, so I can not tell the difference from 404 and other errors.
The part of code shows below:
xdr: function (url, method, data, callback, errback) {
var req;
if(typeof XDomainRequest !== "undefined") {
req = new XDomainRequest();
req.open(method, url);
req.onerror = function() {
// I want to handle specific 404 error here
callback(req.responseText);
};
req.onload = function() {
callback(req.responseText);
};
req.send(data);
} else if( typeof XMLHttpRequest !== "undefined") {
req = new XMLHttpRequest();
if('withCredentials' in req) {
req.open(method, url, true);
req.onerror = errback;
req.onreadystatechange = function() {
if (req.readyState === 4) {
if ((req.status >= 200 && req.status < 400) || req.status ==404 ) {
callback(req.responseText);
} else {
errback(new Error('Response returned with non-OK status'));
}
}
};
req.send(data);
}
} else {
errback(new Error('CORS not supported'));
}
}
The XMLHttpRequest works fine and all other browser are working except in IE.
Unfortunately the XDomainRequest object does not provide anyway of accessing the response HTTP status code. The only properties you can access on the XDR instance are: constructor, contentType, responseText, and timeout; and the only methods are: abort(), open(), and send(). On top of that, the error handler doesn't even get passed any arguments.

Categories