CORS missmatch because of http
I don't understand why i get this error.
sub.domain.app/:1 XMLHttpRequest cannot load http://domain.app/wc-api/v3. The 'Access-Control-Allow-Origin' header contains the invalid value 'sub.domain.app'. Origin 'http://sub.domain.app' is therefore not allowed access.
The site domain.app is a wordpress install and sub.domain is just static html. And I the error occurs when i try to fetch via ajax (vue-router).
Both the domains are on homestead. And I have set up nginx to allow the subdomain to do CORS requests.
location / {
try_files $uri $uri/ /index.php?$query_string;
add_header 'Access-Control-Allow-Origin' "http://sub.domain.app";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
I'm hoping someone smarter than me can help me solv this. Thanks in advance!
Answer
It looks like you want to allow requests for the main domain and a subdomain. CORS specification does not permit that in a single header. Either the exact domain or '*'. You have to dynamically check the domain and set that in the header.
With NGINX:
server {
root /path/to/your/stuff;
index index.html index.htm;
set $cors "";
if ($http_origin ~* (.*\.domain.com)) {
set $cors "true";
}
server_name domain.com;
location / {
if ($cors = "true") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
}
if ($request_method = OPTIONS) {
return 204;
}
}
}
With PHP
Examine $_SERVER['HTTP_HOST']
and search it for your desired (sub)domains, and then conditionally set your CORS headers with PHP.
So, something like this:
$allowed_hosts = array('sub.domain.app', 'domain.app');
if (in_array($allowed_hosts, $_SERVER['HTTP_HOST'])) {
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_HOST']);
}
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM