Install Nginx Module
sudo apt-get install nginx-extras
/etc/nginx/nginx.conf
http {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE, HEAD';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: auth,Origin,Content-Type,Accept,Authorization';
}
/etc/nginx/sites-enabled/default
location / {
if ($request_method = 'OPTIONS') {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE, HEAD';
more_set_headers 'Access-Control-Max-Age: 1728000';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: auth,Origin,Content-Type,Accept,Authorization';
more_set_headers 'Content-Type: text/plain; charset=UTF-8';
more_set_headers 'Content-Length: 0';
return 204;
}
}
Ref: handling-cors-with-nginx
fetch snippets
// GET With Custom Header
fetch('/api', {
method: 'GET',
headers: {
auth: token
}
})
// GET With URL Parameters
const body = param({
key1: 1,
key2: [2, 3]
});
// /api?key1=1&key2[]=2&key2[]=3
fetch(`/api?${body}`, {
method: 'GET'
})
// POST JSON
fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({...})
})
// POST Form Data
fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: param({
...
})
})
Ref: param()