How to resolve Access-Control-Allow-Origin error? - javascript

I know there are lot of queries already posted related to this issue. But I am still not able to resolve the error.
I am getting,
XMLHttpRequest cannot load http://localhost:100/test/test1.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
To resolve I tried following -
I used --allow-file-access-from-files --disable-web-security, while launching chrome.exe. (Not working)
I put header('Access-Control-Allow-Origin:*'); in php, after <?php tag. (Sometimes it works, but not always).
In ajax, $.ajax({crossDomain:true}) I have included. (Not working).

Add these three lines:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

There's a manual:
http://enable-cors.org/
This presents a variety of options depending your server setup (as well as explain the topic fairly well).
Note that the previous answers are totally correct for PHP... header('Access-Control-Allow-Origin:*'); if you're having problems, remember that you need to send that header before you send any body output to the buffer.

Simple solution to get this done is you need to add header to server side
header('Access-Control-Allow-Origin:*')
In one of my golang API server,I added below header code to allow CORS
Response.Header().Set("Access-Control-Allow-Origin", "*")

Related

Safari 10.1: XMLHttpRequest with query parameters cannot load due to access control checks

When trying a CORS request on Safari 10.1, on an URL which includes query parameters (e.g. https://example.com/api?v=1), Safari says
XMLHttpRequest cannot load due to access control checks
Chrome/Firefox works fine.
On requests from the page without the ?v=1, Safari works fine too.
I tried changing the server response header from
Access-Control-Allow-Origin: https://example.com
to
Access-Control-Allow-Origin: https://example.com/api?v=1
but that breaks Chrome.
Any suggestions?
You're running into CORS issues.
Some possible causes:
The header Access-Control-Allow-Origin can only be set on server side, not in your clients script. (You did not make clear you did that correctly.)
Are you sure the protocol (http vs https vs maybe even file) is exactly the same?
If you may have multiple sub domains you need to setup your config (e.g. Apache) with something like "^http(s)?://(.+\.)?test\.com$
.
The ^ marks the start of the line to prevent anything preceeding this url. You need a protocol and allowing both here. A subdomain is optional. And the $ marks the end of line (you don't need to set sub-pages, because origin is only host based).
As stated here adding Access-Control-Allow-Headers: Origin to the server configuration as well may be a solution. Try to compare the actual requests made my Safari to the successfull requests done by Firefox or Chrome to spot possible missing Headers as well (and maybe compare them to your server configuration as well).
If anyone comes across this error, it just occurred in the application I was building. In my case, it turned out to be a trailing / in the uri, which caused a 301 response, which was for some reason interpreted by Safari as a 500 response.
Trying following might work -
Access-Control-Allow-Origin: <origin> | *
The problem is because it is necessary to be more specific in the data of the cors this does not happen in the other operating systems that do interpret it
This one worked for me for a back in php
header ("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header ("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header ("Allow: GET, POST, OPTIONS, PUT, DELETE");
$ method = $ _SERVER ['REQUEST_METHOD'];
if ($ method == "OPTIONS") {
     die ();
}
Your server needs to reply to the OPTIONS http method. Not only to GET/POST/PUT/DELETE. Safari silently requests this hidden in the background. You can discover this with a MITM-attack on the connection, e.g. Fiddler.
The OPTIONS request at least needs to respond with the Cross-Origin Resource Sharing (CORS) headers, e.g.:
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Additionally: Your Web Application Firewall (WAF) or Application Security Manager (ASM) needs to allow the OPTIONS request to pass through to your server. Often this is blocked by default, because it gives some slivers of information about the attack surface variables (http methods & headers) used by your API.
You should check the method type you calling may be - PUT, POST, GET etc.

Angular2 http.get preflight issues

I am currently using angular2's HTTP to POST and GET data from my custom api.
The API is in PHP and the end points etc have been tested and work fine.
The issue I am getting is any time I set the GET Authorization header, I get the following error message in Chrome console:
Response for preflight has invalid HTTP status code 404
I have set my API's headers to allow access from remote origins with the following:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH ,DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
Yes I am running my angular project on localhost, I have a POST request that happens without the Authoriazation header set and it works fine, I have also removed the Authorization header from my GET request and it then works fine (But that end point needs the Authorization header to send my JWT to my API)
Am I doing something wrong? Should I be settings other headers, I have tested the endpoint in Postman and all is working fine.
EDIT
I have also edited my Hosts file to have a tld point to my local and also one for the API which is an IP on my local machine....
So my origin is: website.com
My API: api.website.com
I have changed my
Access-Control-Allow-Origin: http://website.com:3000
I found the issue.
My router was only accepting $_POST and $_GET methods,
Chrome sends a OPTIONS method before sending the POST or GET to confirm the Origin.
For now I have just added:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");exit;
}
So now when a OPTION request comes through it just returns the headers that are needed to allow my POST and GET requests
The easiest way to handle this if you have control of the responding server is to add a response header for:
Access-Control-Allow-Origin: *
This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:
<?php header('Access-Control-Allow-Origin: *'); ?>
You can just put the Header set Access-Control-Allow-Origin * setting in the Apache configuration or htaccess file. It just work like a charm.
From the comments, this is an important note: the wildcard is going to allow any domain to send requests to your host. I recommend replacing the asterisk with a specific domain that you will be running scripts on. While you are going to live.
refer Origin is not allowed by Access-Control-Allow-Origin

XMLHttpRequest cannot load - Origin 'null' is therefore not allowed access

I am doing a login to connect through a service layer to a Linux server that has sap b1, and I get the following error.
XMLHttpRequest cannot load https://hanab1:50000/b1s/v1/Login. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.
I find from google chrome and despite attempts, always the same error is generated, the funny thing is that when we perform the video https://www.youtube.com/watch?v=ilDH8nhnp4o,I get the error above dimensioned, but when I enter the URL directly the next line https://hanab1:50000/B1S/v1, see I have access to all information.
If anyone can help me in advance I thank you for your collaboration and interest.
In simple words, you cannot. To enable the Access Control, you need to change the way, the server sends you the headers. If your server is a PHP based one:
<?php
header("Access-Control-Allow-Origin: *");
And for SAP (if it uses Apache), the headers should be:
Header set Access-Control-Allow-Origin "*"
You can learn for other servers from here: I want to add CORS support to my server.

CORS access blocking

I might need some help here.
I was trying to establish a connection with XMLHttpRequest from JavaScript to a PHP Script on another origin.
First thing I noticed was that I got a error from this request which told me that there were header missing. I searched a bit and found this documentation. I modified the header like this:
JS
//this.mozSystem = true;
this.open("POST", url, true);
this.setRequestHeader("Content-type", "application/json");
this.setRequestHeader("ADDON-TO-SERVER", "");
this.setRequestHeader("Content-length", massage.length);
this.setRequestHeader("Connection", "close");
PHP
header("Content-type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Method: POST");
header("Access-Control-Allow-Headers: ADDON-TO-SERVER,Content-type");
And it works ... but I am not sure why in
header("Access-Control-Allow-Headers: ADDON-TO-SERVER,Content-type");
Content-type is needed.
Mozilla told me to add this one, but I though that it would just need one custom header, and isn't Content-type a basic one ?
Could someone tell me why this is needed and tell me if I done everything like it is intended to.
Thanks for any help,
Feirell
As far as headers go in the context of CORS, a Content-type request header with the value of application/json is not considered a “basic one” (to borrow your wording).
In the context of CORS, a Content-type request header is only considered “basic” if its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain.
So your browser will allow a Content-type: application/json request from your Web application to work as expected only if the server you are sending that request to explicitly indicates that it’s OK with receiving such requests. And the way a server does that is by responding with a Access-Control-Allow-Headersheader that contains Content-type.
The rationale for your browser enforcing that restriction is that unless a server explicitly indicates is it OK with certain kinds of cross-origin requests, CORS is not intended to allow Web applications to do any kind of programmatic cross-origin requests that do anything more than what a basic HTML form-element action have always been able to do cross-origin.
And so since before CORS came along, HTML page have always been restricted just to sending application/x-www-form-urlencoded, multipart/form-data, or text/plain requests cross-origin, that’s what the basic CORS behavior is restricted to unless the server opts-in for more.

WordPress JSON API - Request Header Error

I'm working with the WordPress JSON API plugin to make requests to get posts and etc from my blog.
When I try to access a simple url from browser it works perfectly, but when I try to access from my Ionic application this following erros occurs:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Do I need to do something from my WP blog to allow it?
It is most likely due to a cross-origin request. So try adding the below headers in your functions.php file.
function add_cors_http_header(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
}
add_action('init','add_cors_http_header');
Make sure that you haven't already used header in another file, or you will get a nasty error.
Hope it helps you.

Categories

Resources