调用公交API遇CORS错误,启用CORS扩展仍报HTTP状态异常如何解决?
问题
我正在开发一个显示不同公交剩余到站时间的简易网站,调用法兰西岛交通局的API,相关代码如下:
JavaScript代码
function getTime(){ fetch("https://prim.iledefrance-mobilites.fr/marketplace/stop-monitoring/?MonitoringRef=STIF:StopPoint:Q:37144:", { "method": "GET", "headers": { "apiKey": "NoAPIKeyForU", "accept": "application/json" },}) .then(function (response) { console.log(response.status); return response.text(); }).then(function (data) { console.log(data); }) .catch(function (error) { console.log(error.message); }); }; getTime();
HTML页面代码
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Example</title> </head> <body> <div class="details"> </div> <script src="index.js"></script> </body> </html>
测试时遇到CORS错误:
Access to fetch at 'https://prim.iledefrance-mobilites.fr/marketplace/stop-monitoring/?MonitoringRef=STIF:StopPoint:Q:37144:' from origin 'http://localhost' 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浏览器扩展,出现新错误:
It does not have http ok status - 配置
.htaccess文件,无效果 - 尝试使用CORS代理,但不知道具体操作方法
请问该如何解决这个问题?
解决方法
1. 搭建本地CORS代理(推荐方案)
CORS代理通过服务器中转请求,绕开浏览器的同源限制,具体操作:
- 用Node.js快速搭建代理:
- 新建
proxy.js文件,写入代码:
const express = require('express'); const axios = require('axios'); const app = express(); const port = 3001; app.get('/api/stop-monitoring', async (req, res) => { try { const monitoringRef = req.query.MonitoringRef; const response = await axios.get(`https://prim.iledefrance-mobilites.fr/marketplace/stop-monitoring/?MonitoringRef=${monitoringRef}`, { headers: { 'apiKey': '你的真实API密钥', 'accept': 'application/json' } }); res.json(response.data); } catch (error) { res.status(error.response?.status || 500).send(error.message); } }); app.listen(port, () => { console.log(`代理服务器运行在 http://localhost:${port}`); });- 安装依赖:执行
npm install express axios - 启动代理:执行
node proxy.js - 修改前端请求地址为代理地址:
fetch("http://localhost:3001/api/stop-monitoring?MonitoringRef=STIF:StopPoint:Q:37144:") .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.log(err)); - 新建
2. 验证API密钥有效性
你用CORS扩展后出现的It does not have http ok status错误,大概率是API密钥无效导致请求被拒绝。先确认密钥是否在法兰西岛交通局开发者平台正常激活,替换成真实有效的密钥再测试。
3. 不要在前端暴露API密钥
前端代码直接写API密钥会泄露给所有访客,通过代理服务器把密钥存在后端,是安全的做法。
4. 其他备选方案
- 后端中转请求:如果你的网站有后端(PHP/Python等),直接在后端写接口调用公交API,前端再调用自己的后端接口,天然规避CORS问题。
- 检查API是否支持JSONP:查看法兰西岛交通局API文档,若支持JSONP,可改用该方式请求,但此方案安全性较低,仅作为备选。
内容的提问来源于stack exchange,提问作者DasniloYT
相关产品推荐
相关产品推荐

