使用Fetch调用Github Jobs API遭CORS拦截,寻求解决方法
解决Github Jobs API的CORS跨域问题
嘿,这个CORS错误我之前做React项目调用第三方API时也碰到过,本质是浏览器的同源策略在搞事情——你的React项目跑在http://localhost:3000,而Github Jobs API的域名是jobs.github.com,属于不同源,对方服务器又没配置允许你这个源的CORS头,所以浏览器就拦截了请求。给你几个实用的解决办法:
方法一:利用Create React App的内置代理(最简便)
Create React App自带了代理功能,能帮你转发请求避开CORS限制,步骤超简单:
- 打开项目根目录的
package.json,在里面添加一行:"proxy": "https://jobs.github.com" - 修改App.js里的fetch请求,把绝对路径改成相对路径,别忘了把响应转成JSON格式:
componentDidMount() { fetch("/positions.json?description=basf") .then(response => response.json()) .then(data => { console.log(data); this.setState({ character: data }); // 把获取到的数据存到state里 }) .catch(err => console.error(err)); console.log("Hello World"); } - 重启你的React开发服务器,现在请求会通过Create React App的代理转发,就不会触发CORS错误了。
方法二:设置no-cors模式(局限性大,不推荐用来获取数据)
如果只是想让请求不报错,但不需要读取响应内容,可以给fetch加mode: 'no-cors':
fetch("https://jobs.github.com/positions.json?description=basf", { mode: 'no-cors' }) .then(data => console.log(data));
但要注意:这种方式下浏览器会返回一个「不透明响应」,你根本没法读取里面的实际职位数据,所以如果要获取信息的话,这个方法不适用。
方法三:自建Node.js代理服务器(灵活可控)
如果需要更多自定义逻辑,或者你的项目不是用Create React App搭建的,可以自己写个简单的代理服务器:
- 先安装依赖:
npm install express cors node-fetch - 在项目根目录新建
server.js,内容如下:const express = require('express'); const cors = require('cors'); const fetch = require('node-fetch'); const app = express(); // 允许跨域请求 app.use(cors()); // 定义代理接口 app.get('/get-jobs', async (req, res) => { try { const description = req.query.description; // 请求Github Jobs API const apiResponse = await fetch(`https://jobs.github.com/positions.json?description=${description}`); const jobsData = await apiResponse.json(); // 返回数据给前端 res.json(jobsData); } catch (err) { res.status(500).json({ error: err.message }); } }); // 启动代理服务器 app.listen(5000, () => { console.log('代理服务器运行在 http://localhost:5000'); }); - 启动代理服务器:
node server.js - 修改App.js里的fetch请求,指向代理服务器:
componentDidMount() { fetch("http://localhost:5000/get-jobs?description=basf") .then(response => response.json()) .then(data => { console.log(data); this.setState({ character: data }); }) .catch(err => console.error(err)); console.log("Hello World"); }
这样前端请求的是自己的代理服务器,服务器再去请求Github Jobs API,就不受浏览器同源策略限制了。
内容的提问来源于stack exchange,提问作者Shubhankar Banerjee
相关产品推荐
相关产品推荐

