Ошибка is not allowed by access control allow origin

I’m making an Ajax.request to a remote PHP server in a Sencha Touch 2 application (wrapped in PhoneGap).

The response from the server is the following:

XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

How can I fix this problem?

sideshowbarker's user avatar

asked Apr 13, 2012 at 14:50

Ricardo's user avatar

5

I wrote an article on this issue a while back, Cross Domain AJAX.

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 should be noted that this effectively disables CORS protection, which very likely exposes your users to attack. If you don’t know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:

<?php header('Access-Control-Allow-Origin: http://example.com') ?>

user229044's user avatar

user229044

232k40 gold badges328 silver badges336 bronze badges

answered Apr 13, 2012 at 14:54

Matt Mombrea's user avatar

Matt MombreaMatt Mombrea

6,7732 gold badges20 silver badges20 bronze badges

8

If you don’t have control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security.

Note that I wouldn’t use this for normal «web surfing». For reference, see this post: Disable same origin policy in Chrome.

One you use Phonegap to actually build the application and load it onto the device, this won’t be an issue.

Community's user avatar

answered Apr 13, 2012 at 16:50

Travis Webb's user avatar

Travis WebbTravis Webb

14.6k7 gold badges55 silver badges109 bronze badges

10

If you’re using Apache just add:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</ifModule>

in your configuration. This will cause all responses from your webserver to be accessible from any other site on the internet. If you intend to only allow services on your host to be used by a specific server you can replace the * with the URL of the originating server:

Header set Access-Control-Allow-Origin: http://my.origin.host

answered Aug 21, 2012 at 7:15

Reza S's user avatar

Reza SReza S

9,4003 gold badges54 silver badges84 bronze badges

2

If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:

<system.webServer>
  ...

    <httpProtocol>
        <customHeaders>
            <!-- Enable Cross Domain AJAX calls -->
            <remove name="Access-Control-Allow-Origin" />
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Peter Mortensen's user avatar

answered Aug 13, 2013 at 20:56

C. Augusto Proiete's user avatar

3

This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVC as the source of my data. I realize this doesn’t solve the PHP question, but it is related enough to be valuable.

I am using ASP.NET MVC. The blog post from Greg Brant worked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")], that you are able to add to controller actions.

For example:

public class HttpHeaderAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }
    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AppendHeader(Name, Value);
        base.OnResultExecuted(filterContext);
    }
}

And then using it with:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
    return Json( "Some public result" );
}

tagurit's user avatar

tagurit

4945 silver badges13 bronze badges

answered Jun 6, 2013 at 15:24

badMonkey's user avatar

badMonkeybadMonkey

1,6871 gold badge22 silver badges23 bronze badges

1

As Matt Mombrea is correct for the server side, you might run into another problem which is whitelisting rejection.

You have to configure your phonegap.plist. (I am using a old version of phonegap)

For cordova, there might be some changes in the naming and directory. But the steps should be mostly the same.

First select Supporting files > PhoneGap.plist

enter image description here

then under «ExternalHosts»

Add a entry, with a value of perhaps «http://nqatalog.negroesquisso.pt»
I am using * for debugging purposes only.

enter image description here

answered Apr 23, 2012 at 4:46

steve0hh's user avatar

steve0hhsteve0hh

6376 silver badges15 bronze badges

0

This might be handy for anyone who needs to an exception for both ‘www’ and ‘non-www’ versions of a referrer:

 $referrer = $_SERVER['HTTP_REFERER'];
 $parts = parse_url($referrer);
 $domain = $parts['host'];

 if($domain == 'google.com')
 {
         header('Access-Control-Allow-Origin: http://google.com');
 }
 else if($domain == 'www.google.com')
 {
         header('Access-Control-Allow-Origin: http://www.google.com');
 }

answered Jun 18, 2013 at 17:37

lewsid's user avatar

lewsidlewsid

1,9002 gold badges17 silver badges19 bronze badges

1

If you’re writing a Chrome Extension and get this error, then be sure you have added the API’s base URL to your manifest.json‘s permissions block, example:

"permissions": [
    "https://itunes.apple.com/"
]

Jonathan Cross's user avatar

answered Feb 1, 2014 at 18:18

itzg's user avatar

itzgitzg

1,0612 gold badges13 silver badges11 bronze badges

I will give you a simple solution for this one. In my case I don’t have access to a server. In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple:

  1. Create a Chrome browser shortcut
  2. Right click short cut icon -> Properties -> Shortcut -> Target

Simple paste in "C:Program FilesGoogleChromeApplicationchrome.exe" --allow-file-access-from-files --disable-web-security.

The location may differ. Now open Chrome by clicking on that shortcut.

Peter Mortensen's user avatar

answered Oct 16, 2013 at 4:01

Dibish's user avatar

DibishDibish

9,05322 gold badges64 silver badges106 bronze badges

0

I’ve run into this a few times when working with various APIs. Often a quick fix is to add «&callback=?» to the end of a string. Sometimes the ampersand has to be a character code, and sometimes a «?»: «?callback=?» (see Forecast.io API Usage with jQuery)

Community's user avatar

answered Dec 19, 2012 at 0:07

Francis Baptiste's user avatar

This is because of same-origin policy. See more at Mozilla Developer Network or Wikipedia.

Basically, in your example, you to need load the http://nqatalog.negroesquisso.pt/login.php page only from nqatalog.negroesquisso.pt, not localhost.

tagurit's user avatar

tagurit

4945 silver badges13 bronze badges

answered Apr 13, 2012 at 14:51

antyrat's user avatar

antyratantyrat

27.4k9 gold badges75 silver badges76 bronze badges

2

if you’re under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

aydow's user avatar

aydow

3,6232 gold badges22 silver badges39 bronze badges

answered Sep 2, 2015 at 18:31

chispitaos's user avatar

chispitaoschispitaos

7579 silver badges14 bronze badges

0

In Ruby on Rails, you can do in a controller:

headers['Access-Control-Allow-Origin'] = '*'

Peter Mortensen's user avatar

answered Sep 3, 2013 at 15:51

fuzzyalej's user avatar

fuzzyalejfuzzyalej

5,8832 gold badges31 silver badges49 bronze badges

1

If you get this in Angular.js, then make sure you escape your port number like this:

var Project = $resource(
    'http://localhost\:5648/api/...', {'a':'b'}, {
        update: { method: 'PUT' }
    }
);

See here for more info on it.

RevanthKrishnaKumar V.'s user avatar

answered Apr 18, 2013 at 9:23

Marius's user avatar

MariusMarius

3,5793 gold badges27 silver badges30 bronze badges

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS’ responses.

In Chrome, use this extension. If you are on Mozilla check this answer.

answered Apr 7, 2015 at 12:26

forzagreen's user avatar

forzagreenforzagreen

2,47130 silver badges38 bronze badges

0

We also have same problem with phonegap application tested in chrome.
One windows machine we use below batch file everyday before Opening Chrome.
Remember before running this you need to clean all instance of chrome from task manager or you can select chrome to not to run in background.

BATCH: (use cmd)

cd D:Program Files (x86)GoogleChromeApplicationchrome.exe --disable-web-security

RevanthKrishnaKumar V.'s user avatar

answered Mar 11, 2013 at 6:37

abksharma's user avatar

abksharmaabksharma

5767 silver badges25 bronze badges

In Ruby Sinatra

response['Access-Control-Allow-Origin'] = '*' 

for everyone or

response['Access-Control-Allow-Origin'] = 'http://yourdomain.name' 

answered Jun 7, 2015 at 20:16

Mikhail Chuprynski's user avatar

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

RevanthKrishnaKumar V.'s user avatar

answered Sep 9, 2014 at 23:10

Alessandro Annini's user avatar

Problem

The following web browser error message appears when accessing the DeployR landing page for Linux:

Error: Origin is not allowed by Access-Control-Allow-Origin

Solution

This error occurs when DeployR has not started properly. You can start the service again by issuing the following command:

/home/<deploy_user_directory>/deployr/7.<version>/startAll.sh 

Note: There are also some instances when the DeployR server needs to be rebooted due to maintenance & accessing the DeployR landing page directly after the server has rebooted will sometimes give the above error message on your browser. Please make sure that you invoke the startAll.sh script or you can put this script when your Linux server starts up:

For example in RedHat Linux:
On /etc/rc.d/rc.local, you can insert the following lines:

su - <deployr_user> -c '/home/<deploy_user>/deployr/7.<version>/startAll.sh'

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

WordPress sites will work perfectly fine as long as you use it in a simple manner. It will throw you different types of errors, the moment you want to add additional features and third-party scripts. In our earlier article, we have explained about the problem with WP-Cron while using Cloudflare. Similarly, CORS error is another popular WordPress error that many users struggle to fix. In this article, we will explore what is CORS and how to fix CORS errors in WordPress.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. By default, a web browser allows all the requests originated from the same server using same-origin security policy. Here is a precise definition of  same-origin policy from Wikipedia:

Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.

Wikipedia

Now that you can easily understand the purpose of cross-origin. It allows you to successfully load the scripts and other resources from another domain or server. Below is a beautiful image from MDN explaining the concept of same-origin and cross-origin requests.

CORS MDN

Example of CORS and Seeing Errors

Let’s take a case that you are opening a page https://site1.com/page1 which has an embedded JavaScript and calls it from https://site2.com/page2. CORS will tell the browser whether the cross-origin request from site2 is allowed by site 1. Otherwise, browser will block this request and show CORS related errors in the console.

The best example of CORS is using advertisement scripts from third-party domains on your site. Browsers like Chrome, Firefox, Safari and Edge will block the ad scripts if you are not allowing CORS on your server. When you see an advertisement or any other output is not loading on the page, right click on the page and select “Inspect” option. This will open the browser’s developer console and go to “Console” section.

You will see different types of error showing 403, 401 status codes or errors without status code. For example, below is the console errors showing in Google Chrome and the error states clearly “Access to XMLHttpRequest at ‘……’ from origin ‘…..’ has been blocked by CORS policy”. You can also see the reason next to the error stating that “The ‘Access-Control-Allow-Origin’ header has a value ‘…..’ that is not equal to the supplied origin.”

CORS Error in Google Chrome
CORS Error in Google Chrome

The same page when opened in Mac Safari browser will show different errors like below. It shows the error as “Origin ‘….’ is not allowed by Access-Control-Allow-Origin. Status code: 401”. You can also see errors like “XMLHttpRequest cannot load ‘…..’ due to access control checks”.

CORS Error in Safari Browser
CORS Error in Safari Browser

Whenever you see console errors related to access control checks, you can safely assume they are related to CORS issue. As a result, you the script will fail to load and you will not see the advertisement or the expected result on the page.

Now that you understand what is CORS and how to find the related errors in browser console. The next step is to fix the error so that your page loads on browsers without any errors. In simple, you have to add the following code in your .htaccess file to allow cross-origin resource sharing on your server.

Access-Control-Allow-Origin: *

There are three different ways you can achieve this depending upon the scenario.

1. Allowing All Sites

This is the most common way of allowing CORS. If you want to allow any third-party server requests on your site, then add the following code in your htaccess file. The * is used as a wildcard for allowing any third-party domains.

<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>

2. Allow Specific Domain

The above method is not recommended as any hijackers can inject malicious script files on your site and cause trouble. The correct approach is to allow cross-origin resource sharing only from the domain you need. You can replace the * with the name of the domain as given below:

<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: https://site2.com
</ifModule>

Unfortunately, this is not easy to do as you need server side coding to validate the domain allowed in the header access control. Therefore, option #1 is used by many WordPress users as it does not need any additional coding.

3. Allow Specific Files from All Servers

The last option is to restrict the file type you want to allow from third-party servers. For this, you can use the following code indicating the allowed file types in your htaccess file.

<IfModule mod_headers.c>
  <FilesMatch ".(png|css|js)$">
    Header set Access-Control-Allow-Origin: *
  </FilesMatch>
</IfModule>

This code will allow PNG images, CSS and JS files from any servers. You can add fonts and other image file types to allow them in CORS.

Other Considerations

There are few additional considerations you may need to aware when allowing cross-origin resource sharing in WordPress.

  • Some hosting companies needs you to disable their caching for CORS to work. For example, if you are on SiteGround, you need to disable NGINX direct delivery under “Site Tools > Speed > Cache” section.
  • When using Cloudflare or any other CDN with caching setup, you may need to purge the cache completely for the changes to reflect from the origin server.
  • CORS can also create problem when using HTTP and HTTPS protocols. This will generally show as mixed content error in browser console and you need to force using HTTPS on your site to block other protocols.
  • Another consideration is serving static and other resources from subdomain to primary domain. This will work perfectly since both subdomain and primary domains are generally on the same origin server. However, it may also create problems depending upon the setup on your server. You can resolve this problem by specifically mentioning the subdomain as explained above in option #2.

tsepen

На сервере настроены cors — get запросы проходят, при post запросе ошибка

Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response

Если прописать в headers
'Access-Control-Allow-Origin': '*'
То перестают работать даже get запросы


  • Вопрос задан

    более трёх лет назад

  • 5764 просмотра

Пригласить эксперта

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, x-access-token"

const cors = require('cors');
const app = express();

app.use(cors());

или:

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST, PUT');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');

  next();
});


  • Показать ещё
    Загружается…

13 июн. 2023, в 15:58

400 руб./за проект

13 июн. 2023, в 15:58

400 руб./за проект

13 июн. 2023, в 15:58

400 руб./за проект

Минуточку внимания

Published 2022-07-08

When you send an HTTP request with a different domain than your page’s domain (or IP address + port number), a CORS error will occur. A CORS error means that the API server rejected your request. To access other domain API from your web page, the backend server you requested must set some CORS headers in the HTTP response to allow CORS requests. Below are some errors caused by incorrectly set HTTP response headers for CORS requests.

Error information in web browser console

1
2
Access to XMLHttpRequest at 'http://localhost:8081/api' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET http://localhost:8081/api net::ERR_FAILED 302

Solutions

First, check that the URL, Method, and Content-Type you requested are correct.

Make sure the server API is up and running.

Enable CORS requests for your server API. Add Access-Control-Allow-Origin in HTTP response header.

1
2
3
Access-Control-Allow-Origin: *
or
Access-Control-Allow-Origin: http://your_page_domain

For example, in Java web projects.

1
2
3
response.setHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Allow-Origin", "http://localhost");

Reasons

The API is not shared with other origins. You need to update the API CORS policy by set Access-Control-Allow-Origin in response headers.

Error: Method xxx is not allowed

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.

Solutions

Add Access-Control-Allow-Methods: {method_name_in_error_message} in HTTP response header. Note that method names must be capitalized.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Methods", "DELETE");

Reasons

The default allowed HTTP methods for CORS are GET, POST, and HEAD. For other HTTP methods like DELETE or PUT, you need to add it to HTTP response header Access-Control-Allow-Methods.

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Request header field my-header1 is not allowed by Access-Control-Allow-Headers in preflight response.
1
Access to XMLHttpRequest at 'http://localhost:8081/api/get?name=Jack' from origin 'http://localhost' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Solutions

Add Access-Control-Allow-Headers: {header_field_name_in_error_message} in HTTP response header.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Headers", "my-header1");

Reasons

The default allowed HTTP headers for CORS requests are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type (value only be application/x-www-form-urlencoded, multipart/form-data, or text/plain)
  • Range

For other HTTP headers, you need to add them to HTTP response header Access-Control-Allow-Headers.

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: 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.

Solutions

Set the value of Access-Control-Allow-Origin to your page domain instead of * in HTTP response header. And set the value of Access-Control-Allow-Credentials to true.

For example, in Java web projects.

1
2
response.setHeader("Access-Control-Allow-Origin", "http://localhost");
response.setHeader("Access-Control-Allow-Credentials", "true");

Reasons

When you send a CORS request with credentials, you must set a specific domain in Access-Control-Allow-Origin.

CORS request with credentials: withCredentials: true

1
2
3
4
5
6
7
8
9
10
11
12
const xhr = new XMLHttpRequest();
const url = 'http://localhost:8081/api/get';
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
}
}
};
xhr.send();
1
2
3
4
5
6
7
8
9
$.ajax({
url: "http://localhost:8081/api/get",
method: "GET",
xhrFields: {
withCredentials: true
},
}).done(function(res) {
console.log(res);
});

Error information in web browser console

1
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Solutions

Add Access-Control-Allow-Credentials: true in HTTP response header.

For example, in Java web projects.

1
response.setHeader("Access-Control-Allow-Credentials", "true");

Reasons

When the request’s credentials flag is true, the HTTP response header Access-Control-Allow-Credentials should be true.

Понравилась статья? Поделить с друзьями:
  • Ошибка is not a valid win32 application
  • Ошибка is not a valid mysql
  • Ошибка is not a valid key name
  • Ошибка is not a valid integer value как исправить
  • Ошибка is not a valid guid value