Chrome本地HTML无法获取远程JSON,遇CORS错误求解决方案
解决NSE India API的CORS跨域问题
我想从链接 https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050 获取JSON数据,直接在浏览器打开该链接能正常显示内容,但用JavaScript的fetch方法调用时出现CORS错误。目前我用Node.js服务器做中转,但希望优先采用无需中间服务器的解决方案。
我尝试的JavaScript代码如下:
fetch('https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050', { method: 'GET', headers: { 'Accept': 'application/json', }, }) .then(response => response.json()) .then(response => console.log(JSON.stringify(response)))
无需中间服务器的解决方案
1. 添加浏览器请求头模拟正常访问
NSE的API可能会校验请求来源,你可以在fetch里补充几个浏览器常用的请求头,比如User-Agent和Referer,模拟真实的浏览器访问:
fetch('https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050', { method: 'GET', headers: { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'Referer': 'https://www.nseindia.com/' }, }) .then(response => response.json()) .then(response => console.log(JSON.stringify(response))) .catch(err => console.error(err));
很多网站会通过请求头区分爬虫和正常浏览器请求,补充这些头有可能绕过CORS限制
2. 用浏览器扩展临时绕过CORS
如果只是自己调试使用,可以装个浏览器的CORS扩展,比如CORS Unblock或者Allow CORS: Access-Control-Allow-Origin,开启后就能直接在前端页面调用该API,不用改代码。
注意:这类扩展只适合个人调试,不能用到对外发布的网站上
备用方案:Node.js中转服务器
如果上面的方法都不管用,就继续用Node.js做中转,示例代码如下:
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const port = 3000; app.get('/nifty-data', async (req, res) => { try { const apiUrl = 'https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050'; const response = await fetch(apiUrl, { headers: { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } }); const data = await response.json(); res.json(data); } catch (err) { res.status(500).json({ error: err.message }); } }); app.listen(port, () => { console.log(`中转服务器运行在 http://localhost:${port}`); });
然后前端调用自己的中转接口:
fetch('http://localhost:3000/nifty-data') .then(response => response.json()) .then(response => console.log(JSON.stringify(response))) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者Ashish Bindal
相关产品推荐
相关产品推荐

