发送GET请求遇CORS预检错误,请求协助排查及确认问题归属
CORS预请求失败问题排查与解决
问题描述
携带token向后端发送GET请求时出现如下错误:
Access to fetch at 'http://XXX.XX.XXX.XX:8067/v1/api/subscriber/list/1/20' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
已尝试现有解决方案但均无效,请求协助解决该问题,并询问此问题属于前端还是后端问题,对应的前端请求代码如下:
export const getAllSubscribers = async (page, limit) => { const token = localStorage.getItem('token').split(":")[1]; const url = api.allSubscribers(page, limit); const headers = new Headers(); headers.append('Authorization', `Bearer ${token}`); headers.append('Content-Type', 'application/json'); try { const response = await fetch(url, { method: 'GET', headers: headers, }); console.log("response-------", response.headers); if (!response.ok) { throw new Error(`Error fetching subscribers: ${response.statusText}`); } const data = await response.json(); return data; } catch (error) { console.error("Error occurred during allSubscribers request:", error); throw error; } }
问题归属
这个问题属于后端问题。错误核心是浏览器发送的跨域预请求(OPTIONS请求)没有得到后端返回的HTTP 2xx成功状态码,预请求的处理逻辑完全由后端服务器控制,和前端代码无关。
解决步骤
修复后端OPTIONS请求处理逻辑
浏览器发送GET请求前会先发起OPTIONS预请求验证权限,后端必须:- 对OPTIONS请求返回200或204的成功状态码
- 响应头中携带正确的CORS字段:
Access-Control-Allow-Origin: 需包含前端域名http://localhost:5173,或临时设为*(生产环境不推荐)Access-Control-Allow-Methods: 必须包含GET方法Access-Control-Allow-Headers: 必须包含Authorization和Content-Type
- 禁止对OPTIONS请求做token校验,预请求不会携带完整的授权信息,强行校验会直接导致请求失败。
前端代码优化(可选)
GET请求无需设置Content-Type: application/json(GET没有请求体),移除这个头可以简化预请求的校验逻辑,修改后的headers代码:const headers = new Headers(); headers.append('Authorization', `Bearer ${token}`);验证后端服务状态
用Postman直接发送OPTIONS请求到目标接口,检查返回的状态码和响应头是否符合要求,确认后端服务是否能正常接收并处理请求。
内容的提问来源于stack exchange,提问作者Jamal Fakhriddinov
相关产品推荐
相关产品推荐

