![](/img/trans.png)
[英]Cross-Origin Request Blocked: (Reason: CORS header 'Access-Control-Allow-Origin' missing)
[英]Cross-Origin Request Blocked: CORS header ‘Access-Control-Allow-Origin’ missing
我正在运行一个用于路由目的的快速服务器,客户端页面使用 axios 来获取url 。 我已经尝试了这一整天我能找到的所有可能的解决方案,但没有成功。
但是,我可以通过单击开发人员控制台的响应选项卡在响应中看到 json 页面。
服务器页面
const express = require('express')
const cors = require('cors')
const app = express()
app.use(
cors({
credentials: true,
origin: [
'http://localhost:8080'
]
}),
)
app.options('*', cors());
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile( __dirname + "/public/" + "index.html" );
})
客户页面
var nse = axios.create(); // delete nse.defaults.headers.common["Access-Control-Allow-Origin"]; //nse.defaults.headers.common['Access-Control-Allow-Origin']='http://localhost:8081'; // nse.defaults.headers.common['Access-Control-Allow-Methods']='POST, OPTIONS'; // nse.defaults.headers.common['Access-Control-Max-Age']= 86400; // nse.defaults.headers.common['Access-Control-Allow-Headers']= 'Origin, Content-Type, Accept'; nse.get('https://www1.nseindia.com/live_market/dynaContent/live_watch/stock_watch/liveIndexWatchData.json',{ crossdomain: true }).then(resp => { console.log("xxxxx"); data = resp.data.data; window.alert("hi"); }).catch(function (error) { if (error.response) { console.log(error.response.data); console.log(error.response.status); } });
我在 firefox 浏览器的开发人员控制台中收到以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www1.nseindia.com/live_market/dynaContent/live_watch/stock_watch/liveIndexWatchData.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
我相信这是一个棘手的难题。 请帮助我解决此错误,以便我能够以编程方式读取 JSON 响应。
服务器识别了请求,但它没有将 Access-Control-Allow-Origin 标头附加到响应中。 浏览器期待这一点,因为它不存在,浏览器会抛出错误并阻止访问响应数据(即使您可以在开发工具中看到它)。
您需要在服务器上配置 CORS 以允许来自您发送请求的源的请求。
给寻找快递 cors 代码的人
app.use(cors({
origin: [
'https://www.nseindia.com' //nse url
],
optionsSuccessStatus: 200
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.