AJAX post error : Refused to set unsafe header "Connection" - javascript

I have the following custom ajax function that posts data back to a PHP file. Everytime the post of data happens I get the following two errors :
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
Code :
function passposturl(url1, params, obj)
{
//url1 = url1+"&sid="+Math.random();
xmlHttp = get_xmlhttp_obj();
xmlHttp.loadflag = obj;
xmlHttp.open("POST", url1, true);
//alert(url1);
//alert(params);
//alert(obj);
//alert(params.length);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function ()
{
stateChanged(xmlHttp);
};
xmlHttp.send(params);
}
What am I doing wrong?

Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Section 4.6.2 of the W3C XMLHttpRequest Level 1 spec lists headers that "are controlled by the user agent" and not allowed to be set with the setRequestHeader() method. Both Connection and Content-length are in that list.
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Related

How to POST json data to the server? (CORS error)

My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet

Ebay Trading API Get Item Ajax Request

I want to made simple post request on Ebay trading api with javascript Ajax. Here is the call format. I got some error on the following request. can anyone tell me the what wrong with the call .
const findbtn = document.querySelector(".find-item-btn");
findbtn.addEventListener("click", getData);
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
};
const xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">' +
"<ErrorLanguage>en_US</ErrorLanguage>" +
"<WarningLevel>High</WarningLevel>" +
"<ItemID>232789363104</ItemID>" +
"</GetItemRequest>";
xhttp.open("POST", "https://api.ebay.com/ws/api.dll", true);
xhttp.setRequestHeader("X-EBAY-API-COMPATIBILITY-LEVEL", "967");
xhttp.setRequestHeader("X-EBAY-API-DEV-NAME","6cfe5ebb-73c4-465b-ad24-c4f0aea8de0");
xhttp.setRequestHeader("X-EBAY-API-APP-NAME","RegnantC-SaveWix-PRD-3ef66784f-24730a7");
xhttp.setRequestHeader("X-EBAY-API-CERT-NAME","PRD-ef66784f85c1-6c65-4919-bc83-24c6");
xhttp.setRequestHeader("X-EBAY-API-CALL-NAME", "GetItem");
xhttp.setRequestHeader("X-EBAY-API-SITEID", "0");
xhttp.setRequestHeader("Content-Type", "text/xml");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With, Origin, Content-Type, X-Auth-Token");
xhttp.setRequestHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE");
xhttp.setRequestHeader("X-EBAY-API-IAF-TOKEN","v^1.1#i^1#f^0#r^0#p^3#I^3#t^H4sIAAAAAAAAAOVYeWwUVRjv9lJEaIigTUWzTiEeOLtz7e7sh"
);
xhttp.send(xml);
}
and got the following error
1 Access to XMLHttpRequest at 'https://api.ebay.com/ws/api.dll' from origin 'localhost/app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2 POST https://api.ebay.com/ws/api.dll net::ERR_FAILED
Please help me. is the right format for the ajax request
Actually it's causing the CORS error. You can read about it details from here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
And if you want to overcome this issue you can enable CORS from server. I mean send the request through your server.
Or you can also use CORS anywhere header.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
then use this corsHeader appending with your url like this,
xhttp.open("POST", corsHeader+"https://api.ebay.com/ws/api.dll", true);
It'll send the request and currently it's showing error: IAF token supplied is invalid. If you provide proper IAF token then it'll provide you the data.
I'm very new to programming in general so this will not be a technical answer in the least, but.... I did get this to eliminate the CORS error.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
xhttp.open("POST", "https://api.ebay.com/identity/v1/oauth2/token", true);
xhttp.open("POST", corsHeader, true);
I had to go here first and enable temporary access though.
https://cors-anywhere.herokuapp.com/corsdemo
Now when I run this the console is saying:
"This API enables cross-origin requests to anywhere."
If I can figure out how to get any farther I will update this thread.

Access-Control-Allow-Origin Apache SVN endpoint

I would like to make a XmlHttp GET request from client Javascript to a Apache SVN endpoint and I'm facing the following error:
Failed to load http://IP_ADDRESS/svn/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://IP_ADDRESS:3000' is therefore not allowed access.
I've tried set the Header set Access-Control-Allow-Origin "*" in the following files and no success so far.
/etc/apache2/mods-available/dav_svn.conf (the configuration is inside this file)
.htaccess (inside the endpoint root folder)
I'm running out of ideias how to do it.
The Javascript request code:
var xmlhttp = new XMLHttpRequest();
// encodedData = ...
xmlhttp.open('GET', url, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + encodedData);
xmlhttp.withCredentials = true;
xmlhttp.send();
What am I doing wrong?
Have you tried adding the address of the client instead of *?
Header set Access-Control-Allow-Origin "http://IP_ADDRESS:3000"
Also if it doesn't work I would suggest adding these other options:
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"

CORS - No 'Access-Control-Allow-Origin' header is present

I'm hosting a website that has a number of different domain names pointing at it.
lets call the hosted website example.com and the url-forwarded domain names - example-x.com, example-y.com, example-z.com
When the url-forwarded domains are visited, cross domain requests are made back to the host site, example.com.
I'm currently making ajax GET requests to json files and receiving the following error;
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example-x.com' is therefore not allowed
access.
Even though the preflight OPTIONS return a status of 200 and the GET method returns a status of 200.
OPTIONS;
GET
I have set the following CORs headers on the host htaccess;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And i'm call GET using the following ajax request;
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
Removing setRequestHeader("Content-Type", "application/json; charset=UTF-8") from the ajax request has removed the preflight requirement, however the CORs error still persists, the screenshot below shows the request / response of GET, its my guess that the correct htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT
You are trying to retrieve a json by a GET request. This should be a simple request, and it does not need to have a preflight request.
If you look at the requirements for a preflight request from MDN, you can see that setting Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain will cause this preflighted request.
If you look at the content-type from the RFC, it is a "SHOULD" for "a message containing a payload body". But your get request does not have a payload. As a result remove that header from your ajax call.

How to req a page without X-REQUESTED-WITH header in javascript

I want to extract a page by javascript (client based language) the problem is the third-part remote url doesnt not allow ajax request when i do this req without the header X-REQUESTED-WITH it gives the expected data with 200 Success in response but when i req it with that header it give 403 Forbidden with no content in respone .
i want to know how to req a page without the header X-REQUESTED-WITH in javascript , ajax , jquery or any client based language .
Please help me .
thanks
The X-REQUESTED-WITH header is not "standard". jQuery for instance will add it manually.
So by doing a default XHR request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 ) {
console.log('done');
}
};
xhr.open('GET', 'hello=50', true);
xhr.setRequestHeader('FOO', 'BAR');
xhr.send(null);
there will not be this header. In the above simplified example we added a custom FOO request header instead, that is the same thing like jQuery adds the X-REQUESTED-WITH header into its ajax requests.

Categories

Resources