错误跨源请求被阻止:同源策略不允许读取远程资源

问题描述 投票:0回答:1

我正在尝试使用 Grafana API 创建一个组织,但是当使用 Vue 组件中的 axios 执行请求时出现以下错误:

跨源请求被阻止:同源策略不允许读取 http://localhost:8001/api/orgs 上的远程资源。 (原因:CORS请求未成功)。状态码:(空)。

我尝试在 Grafana 配置文件上配置自定义响应标头,但错误仍然存在。

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

创建.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);
  });

请求标头:

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

响应标头:

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

知道如何解决吗? 谢谢

axios cors grafana
1个回答
0
投票

您可以尝试名为“允许 CORS”的 Chrome 扩展

© www.soinside.com 2019 - 2024. All rights reserved.