I am using axios with react. and trying to send an API call to another domain (ngnix, laravel). I have did all the things to solve the CORS error, still I am getting this :
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘*, https://www.assamhut.com, *’).
Axios Code:
const API_ROUTE = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-type': 'application/json',
"Key": token,
"Id": user_id
}
});
export async function login_user(email, password) {
await csrf_token();
var result = await API_ROUTE.post('/login', {
email: email,
password: password
});
return result.data;
}
Laravel CORS middleware:
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Ngix Server:
server {
server_name api.assamhut.com www.api.assamhut.com;
root /var/www/api.assamhut.com/public;
index index.php;
charset utf-8;
add_header X-Frame-Options "*";
add_header X-Content-Type-Options "nosniff";
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location / {
try_files $uri $uri/ /index.php?$query_string;
add_header 'Access-Control-Allow-Origin' "*" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
# required to be able to read Authorization header in frontend
#add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}
error_page 404 /index.php;
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /.(?!well-known).* {
deny all;
}
location ~ /.ht {
deny all;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.assamhut.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.assamhut.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = api.assamhut.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name api.assamhut.com www.api.assamhut.com;
return 404; # managed by Certbot
}
3
Answers
The
Access-Control-Allow-Origin
is set inside response headers, not requests. In your Laravel application (the one you try to send your request to), check the CORS settings under theconfigcors.php
file.For Laravel 7 and later, it should be something like this to allow all origins/methods:
For laravel earlier than 7, you can use this package:
https://github.com/fruitcake/laravel-cors (FYI, this package is used in laravel 7 and 8 out of box)
You can check the response headers by simply sending a normal request to the server using Postman or any other browser and you should see something like
access-control-allow-origin: *
in the response header.If the Laravel config and the response header differ, make sure that if the application is behind a reverse proxy, cloud firewalls or services like that, they do not override response headers.
Also allow headers.
Ex:
Handle cors error
create a middleware with name "Cors" : php artisan make:middleware Cors
open the Kernel add the cors created "AppHttpMiddlewareCors::class" as the last item inside the $middleware and not inside $middlewareGroups
inside cors middleware add the following code:
public function handle($request, Closure $next)
{
}