使用Fetch连接GraphQL API遭遇CORS错误,求解决方法
跨域请求失败排查求助
近两天一直在查阅CORS相关资料,尝试各种方案组合,但问题仍未解决。
使用Node.js安装了graphql、express和express-graphql,GraphiQL可视化页面运行正常,服务端监听6969端口。前端通过全局安装的Node.js web-server运行在8000端口,向API发起请求时,浏览器抛出如下错误:
Access to fetch at 'http://127.0.0.1:6969/graphql' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
疑惑点
两者同源为何还会出现CORS错误?是因为端口不同吗?
已尝试的解决方案
- 安装并配置
cors包,无任何变化 - 设置请求
mode: 'no-cors',返回400 Bad Request,且不需要不透明响应 - 添加
mode: 'cors'和credentials: 'include'配置,问题依旧 - 修改请求头,试过的配置如下:
let headers = new Headers() headers.append('Content-Type', 'application/json') headers.append('Accept', 'application/json') headers.append('Origin',' http://127.0.0.1:6969/graphql') headers.append('Access-Control-Allow-Origin', 'http://127.0.0.1:6969/graphql') headers.append('Access-Control-Allow-Origin', '*') headers.append('Access-Control-Allow-Credentials', 'true') headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
- 从不同IP地址发起请求,仍无法解决错误
请求代码其余部分
fetch(' http://127.0.0.1:6969/graphql', { // mode: 'cors', // mode: 'no-cors', credentials: 'include', method: 'POST', headers: headers, // headers: {'Content-Type': 'application/json'}, body: JSON.stringify(requestBody), }) .then(res => { if (res.status !== 200 && res.status !== 201) { throw new Error('Failed HTTP request!') } return res.json() }) .then(resData => { window.thisDiv.innerHTML = resData.data }) .catch(err => { window.thisDiv.innerHTML = `Server error! ${err}` })
内容的提问来源于stack exchange,提问作者agiopnl
相关产品推荐
相关产品推荐

