I'm trying to use the Grafana API to create an Organization but when perform the request with axios from the Vue componenet got the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8001/api/orgs. (Reason: CORS request did not succeed). Status code: (null).
I've tried to config custom response headers on Grafana config file but the error still.
grafana.ini:
[server.custom_response_headers]
Access-Control-Allow-Origin = http://localhost:8005
Access-Control-Allow-Methods = *
Access-Control-Allow-Headers = Content-Type,Authorization
Access-Control-Allow-Credentials = true
Create.vue:
const customOptions = {
headers: {
"Content-Type": "application/json"
},
auth: {
username: import.meta.env.VITE_GRAFANA_API_USER,
password: import.meta.env.VITE_GRAFANA_API_PASSWORD
},
withCredentials: true
}
const data = {
name: "Example name"
}
axios.post('http://localhost:8001/api/orgs', data, customOptions)
.then((response) => {
organization.value = response;
})
.catch((error) => {
console.log(error);
});
Request headers:
OPTIONS /api/orgs HTTP/1.1
Host: localhost:8001
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:131.0) Gecko/20100101 Firefox/131.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type
Referer: http://localhost:8005/
Origin: http://localhost:8005
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Priority: u=4
Response headers:
HTTP/1.1 401 Unauthorized
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: http://localhost:8005
Cache-Control: no-store
Content-Type: application/json; charset=UTF-8
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block
Date: Wed, 23 Oct 2024 07:37:34 GMT
Content-Length: 102
Any idea how to solve it? Thanks
Grafana doesn't manage custom headers and the config [server.custom_response_headers]
doesn't works either. So the solution is to use Nginx as reverse proxy.
grafana.conf:
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' '*' always;
add_header 'Access-Control-Allow-Headers' 'x-grafana-org-id,x-grafana-user-id, Sec-Fetch-Site,Sec-Fetch-Mode,Sec-Fetch-Dest,Connection,Origin,Referer,Access-Control-Request-Headers,Access-Control-Request-Method,Accept-Encoding,Accept-Language,Accept,Host,Content-Type,Authorization,User-Agent,X-Requested-With,Cache-Control,Content-Type' always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Content-Type' 'application/json; charset=utf-8';
return 204;
}
add_header 'Access-Control-Allow-Origin' $http_origin;