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 App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $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
}