我试图通过javascript获取url,但我得到了cors保护错误,我无法找出我应该如何修复
这是我的代码
<script>
fetch("https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut",
{
mode: 'cors',
credentials: 'include',
method: 'GET',
header: {
'Access-Control-Allow-Origin':'*',}
}).then(
res => {
res.json().then(
data => {
// console.log(data.Algo);
if (data.Algo.length > 10) {
var temp = "";
data.Algo.forEach((itemData) => {
temp +="<tr>";
temp +="<td class=" + "col-md-8" + ">" + itemData.underlying + "</td>";
temp += "<td class=" + "col-md-8" + ">" + itemData.identifier + "</td>";
temp += "<td class=" + "col-md-8>" + itemData.instrumentType + "</td>";
temp += "<td class=" + "col-md-8" + ">" + itemData.contract + "</td></tr>";
}
);
document.getElementById('data').innerHTML = temp;
}
}
)
}
)</script>
如何修复CORS头访问控制允许原点丢失?
=>如果服务器在您的控制之下,通过将请求站点的来源添加到access - control - allow - origin头的值中,将其添加到允许访问的域集中。您还可以配置一个站点,允许任何站点通过使用正确的域访问它。示例:Access-Control-Allow-Origin:"http://www.my-domain.example">
Access-Control-Allow-Origin: "*"=比;这是用于公共api,而不是工业或个人api。
const url =
"https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut";
fetch(url, {
mode: "cors",
credentials: "include",
method: "GET",
headers: { "Access-Control-Allow-Origin": "*" },
}).then((res) => {
res.json().then((data) => {
console.log(data.Algo);
/*
if (data.Algo.length > 10) {
var temp = "";
data.Algo.forEach((itemData) => {
temp += "";
temp += "" + itemData.underlying + "";
temp += "" + itemData.identifier + "";
temp += "" + itemData.instrumentType + "";
temp += "" + itemData.contract + "";
});
document.getElementById("data").innerHTML = temp;
}
*/
});
});
你的代码中有一个小错误,我已经修复了。如果你可以访问域名,现在可以尝试将*替换为实际的域名来源