CORS error when fetching api from its own domain - javascript

One of app users constantly has an error when trying to fetch api from the same domain. This error occurs in Chrome only, other browsers are OK at his computer. He also tried to install Chrome CORS extention, but no luck. Does anybody has any idea why this might happen?
Error text below:
Failed to load http://my-app.com/api/v1/scoreboard: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.my-app.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If www and non www causing the problems of CORS. Then in my opinion you can set redirection of non WWW URL to WWW URL. It can be achieved using .htaccess or changing some settings on c-panel
Here the related answer Redirect non-www to www in .htaccess
Another option is to set cors headers on server side.
Hope it helps

This depends on several things but usually calling code should not have any special configuration. instead your server side must decide to reject or allow the request. in case you can have a .htaccess file on your server side try to add this lines.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT,PATCH"
Header set Access-Control-Allow-Headers "Content-Type,Authorization"
</IfModule>
Do not forget to add OPTIONS method in your allowed method list. Thats because the browser always checks the end-point availability by sending an OPTIONS request.

Adding 301 redirect from www to no-www domain name worked for me. Found solution here Nginx no-www to www and www to no-www

Related

How to fix blocked redirect due to CORS issues?

Here is my setup:
Running a local angular application on port 4200
Running an API using Deno on port 4300.
I have a use case where a client call at some api endpoint http://localhost:4300/foo, needs to redirect the user to another portion of the front end, say http://localhost:4200/bar#baz.
Currently this fails with the following error:
Access to XMLHttpRequest at 'http://localhost:4200/bar#baz' (redirected from 'http://localhost:4300/foo') from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I have tried disabling/allowing cors on the API:
ctx.response.headers.set('Acces-Control-Allow-Origin','*');
ctx.response.headers.set('Acces-Control-Allow-Headers','*');
ctx.response.headers.set('Acces-Control-Allow-Methods','*');
ctx.response.headers.set('Access-Control-Allow-Credentials','true');
But this does not work.
Any ideas on how to fix this? Without setting up a proxy or installing a browser plugin.
Thanks!
See MDN:
The value "*" only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal header name "*" without special semantics. Note that the Authorization header can't be wildcarded and always needs to be listed explicitly.
You are making a request with credentials therefore you can't use * as a wildcard and have to be explicit about which headers you are using.

How to solve CORS Origin issue when trying to get data of a json file from localhost

I was trying to get the data from a json file (which is on the remote server) from localhost and I am getting error 'from origin 'http://localhost:5000' 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.'
Below is the code I used to send the get request.
$.ajax({
url: 'http://abc/some.json',
type: "GET",
dataType: "json",
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*",
'Content-Type':'application/json'
},
success: function (data) {
alert(data);
chatbotConfig = data;
console.log(chatbotConfig);
}
})
I am able to get the data using postman. I understand that postman is not a browser so it is not limited by CORS policy. But I am able to download the content from json file directly from the browser. Nit able to understand why I am facing issue when I tried to access from localhost. Can any one please help me to resolve this issue.
Well, the CORS error may lie in different layers of your application. Usually, by allowing all (*) origins and headers in the server-side, your problem should be fixed. But sometimes it won't and it lies somewhere else like your HTTP request header or body, DNS settings (Making sure there are no third-party DNS set in your network by yourself through the OS), or browser settings. So I will describe all of the possible solutions here shortly.
NOTE: You can read more about CORS policy here.
How to solve CORS error
If you have access to your server-side settings and/or options you need to make sure (Or if you don't you need to ask your backend developer) that everything set correctly there or not. So the steps will be as follows:
First of all, you need to make sure your server configs for CORS are set correctly.
So for example, if you are using Apache you can set the CORS policy in your .htaccess file like this (or simply check if it exists):
// This will allow all origins to access your server
Header set Access-Control-Allow-Origin "*" // You can set * to whatever domain
Header add Access-Control-Allow-Methods "*"
If you are using nodeJS you can check or set it like this:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
If you are using Nginx you can check or set it in nginx.conf like this:
server {
location / {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "*";
}
}
If you use any other service for your server-side you should read the documentation about it, but all of them are actually same.
If you checked the above step and CORS policy was set correctly in your server-side, you may need to check your HTTP request and make sure everything is set correctly there. For example, there is no need to add these two headers
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*",
in your request, because they do not exist as a header in the client-side. Wrong HTTP request API end-point address or options (like dataType), wrong HTTP request body or headers may also cause the CORS error for your here. So you need to check them all and make sure you are set them correctly.
If none of the above was the problem you can try two other approaches. I mostly encourage to use the second one if none of the above solves your problem.
Mapping your localhost to a URL using your hosts file (Usually lies under etc folder in each operating system). You can do that like this (But it's better to read the documentation for each OS).
127.0.0.1 www.test.com ## map 127.0.0.1 to www.test.com
## or
localhost www.test.com
NOTE: Usually it is better to avoid this approach.
Use browser plugins like Allow CORS.
Basically if you clearly look into the issue logs:
'from origin 'http://localhost:5000' 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
It's saying CORS not enabled at resource. which means it need to be fixed or allowed at server side.

Purge X-CSRF-TOKEN for visitors to fix XMLHttpRequest being blocked by CORS policy

I've just switched over a website from one host to a different host and for some reason we're getting multiple of the following errors when trying to access a third party API
Access to XMLHttpRequest at 'https://externalwebsite.com/api/' from origin 'https://www.mainwebsite.com.au' has been blocked by CORS policy: Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
The .htaccess file has a CORS policy to allow these connections:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
I can see the old host has set the following cookies, which when I deleted them on my system it allowed the website to work normally:
XSRF-TOKEN 1551054855|ZxDIR_16hNnw .www.mainwebsite.com
hs 1333923782 .www.mainwebsite.com
svSession 253f275579e7747b6495ca6ff45ba024da3bd3b36906f5ac14b709de48792403faf1d3bbff2205d92d2e9a8de90d4b101e60994d53964e647acf411e4f798bcd4c6094311de4bdfbf81f1c6cdfaa3e9de1f5fc736f232b0c584f30f1f7d232d9 .www.mainwebsite.com
How can I include some PHP or Javascript to purge those cookies for anyone who loads the website so that it loads normally for those that have visited the website in the past?
If you can give me some more info of your front end framework I will explain it more clearly.
Possible solution : on page load add script to remove cookies
$(window).load(function() {
$.cookies.del('name_of_your_cookie');
});
This will remove cookies now just add a read cookie command and a condition that will check if cookies are old and need to be removed.
you can use document.cookie to read cookies and parse to check for key values.
Ping me in case of any query :)

error int the Failed to set referrer policy

I'm getting the following error in my chrome console for a Wordpress site I'm working on.
Failed to set referrer policy: The
value 'http://example.com/comic/' is not one of 'always', 'default',
'never', 'no-referrer', 'no-referrer-when-downgrade', 'origin',
'origin-when-crossorigin', or 'unsafe-url'. The referrer policy has
been left unchanged.
It's reffereing to this line in the <head> of the HTML document...
<meta name="Referrer" content="http://example.com/comic/" />
I'm vieing the page over http, not https.
What is causing this issue and how can I fix it?
Go into your .htaccess file and change the following:
Header set Referrer-Policy ""
to
Header set Referrer-Policy "origin"
That should fix the issue.
The reason is more than likely because you don’t have correct permissions on your .htaccess file that allows w3tc to make the changes it needs to.
Here 's the definition taken from the specs:
A referrer policy modifies the algorithm used to populate the Referer header when fetching subresources, prefetching, or performing navigations.
Every environment settings object has an algorithm for obtaining a referrer policy, which is used by default for all requests with that environment settings object as their request client.
Therefore Referral policy deals with what information (related to the url) the browser ships to a server to retrieve an external resource.
The options for the content attribute listed in the specs are :
no-referrer which specifies that no referrer information is to be sent along with requests made from a particular request client to any origin. The header will be omitted entirely.
no-referrer-when-downgrade doesn't send Referrer header to non priori authenticated url (if an https url links to an http url no header is sent)
same-origin policy specifies that a full URL, stripped for use as a referrer, is sent as referrer information when making same-origin requests from a particular request client. while Cross-origin requests won't contain referrer information.
origin sends the scheme, host, and port (basically, the subdomain) stripped of the full URL as a referrer, i.e. https://moz.com/example.html would simply send https://moz.com for all.
origin-when-cross-origin sends the format described in origin to cross-origin, while a full stripped URL is sent to same origin requests.
unsafe-url policy specifies that a full URL, stripped for use as a referrer, is sent along with both cross-origin requests and same-origin requests made from a particular request client.
it's unsafe because it will leak origins and paths from TLS-protected resources to insecure origins.
The empty string "" corresponds to no referrer policy, causing a fallback to a referrer policy defined elsewhere, or in the case where no such higher-level policy is available, defaulting to no-referrer-when-downgrade.
always behaves like unsafe-url.
you can manually find and change as following in .htaccess file :
<IfModule mod_headers.c>
Header set Referrer-Policy ""
</IfModule>
to
<IfModule mod_headers.c>
Header set Referrer-Policy "origin"
</IfModule>
Chrome Inspection Console showed me the same Error for my Wordpress sites which have W3 Total Cache installed.
"Failed to set referrer policy: The value '' is not one of 'no-referrer', 'no-referrer-
when-downgrade', 'origin', 'origin-when-cross-origin'"
and I tried to update the .htaccess file as indicated in the above answer. This fixed the Chrome Inspection Console error but it returned a few moments later.
Checking the Dashboard of W3 Total Cache Performance ->Browser Cache-> Referrer Policy-> Directive, this entry was showing blank.
Selecting 'origin' from the dropdown resulted in .htaccess being updated with the same value 'origin'
"Referer" as a header is spelled without the double R. Maybe with the double R, it's matching against a different header than the one you mean.
In my case, www. was missing in the API URL, while www. was present on the form page. Just ensure your API URL has www. if your page has it too.

SEC7118: XMLHttpRequest CORS - IE Console message

I am using CORS POST request with everything taken care as given #http://www.html5rocks.com/en/tutorials/cors/
Server sets Response header to:
'Access-Control-Allow-Origin':'*' and I can see this header value in IE developer tool.
But on IE10 browser I see console message as "SEC7118: XMLHttpRequest for http:// required Cross Origin Resource Sharing (CORS).
When I check on Microsoft site it has below given explanation.
http://msdn.microsoft.com/en-us/ie/dn423949(v=vs.94).aspx
SEC7118
Description:
"XMLHttpRequest for [URL] required Cross Origin Resource Sharing (CORS). "
An XMLHttpRequest was made to a domain that was different than your page's domain. This requires the server to return an "Access-Control-Allow-Origin" header in its response headers, but one was not returned.
Suggested Fix:
The server must support CORS requests and return an appropriate "Access-Control-Allow-Origin" header with the resource. See CORS for XHR in IE10 for more info about CORS in response headers.
Questions:
I want to know if this console message is an ERROR ??
Will this cause any failures ??
Why do I get this message even after setting response header 'Access-Control-Allow-Origin' value to '*'??
Does 'Access-Control-Allow-Origin' value has to be origin name for
IE10 to work? I know * is not a very good option, But does IE
requires exact origin name ??
I kept URL's and cookie details hidden from these images.
From MSDN:
Security error codes are in the form SEC7xxx [In IE]
Pertaining to SEC7118:
An XMLHttpRequest was made to a domain that was different than your page's domain. This requires the server to return an "Access-Control-Allow-Origin" header in its response headers, but one was not returned.
Note This error code was removed in IE11 on Windows 10. It remains in IE11 for Windows 8.1 and Windows 7.
So it is technically viewed as an error from IE's perspective, but certainly isn't one (hence why it is going away). Access-Control-Allow-Origin is set on a resource, but isn't necessarily sent back with the request. If a specified resource DOESN'T have Access-Control-Allow-Origin:* (or a domain), the resource would not be accessible and the server would likely return a 503 or 404 and you would see a true error message in the console similar to the below:
XMLHttpRequest cannot load http://example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://blog.example.com' is therefore not allowed access.
I encountered SEC7118 when CORS was set up correctly. I verified that the requests were completing with status 200 using the network debugger. So, you can disregard this message if your application is otherwise functioning properly.
I have seen this error in IE11:
SEC7118: XMLHttpRequest for http:// required Cross Origin Resource Sharing (CORS)
Adding the following to my .htaccess fixed it:
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
I had this same issue. It has to do with Internet Explorer's handing of third party cookies. You can fix this issue by going into Tools>Internet Options then selecting the Privacy tab. If you change the setting to "Accept All Cookies" you will no longer see that message.
The safer way to do this would be to click on the "Sites" button and allow cookies from your site's url.

Categories

Resources