node.js - CORS-错误/使用带有数据表的托管文件?
问题描述
我想使用 datatables.net https://www.rapidtech1898.com/aaadownload/arrays.txt阅读这个 txt 文件
但是,当我想将文件与以下文件一起使用时,输出不起作用我在 chrome 检查器中出现此错误:(数据表未按原样读取,检查器向我显示)
(起初我在本地有 txt 文件,并读到使用带有本地文件的 chrome 存在一些问题 - 但这是一个“正常”的 http 链接,不是吗? - 为什么这仍然没有按预期工作?
我有一个 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container py-5">
<header class="text-center text-white">
<h1 class="display-4">Levermann Scores</h1>
</header>
<div class="row py-5">
<div class="col-lg-10 mx-auto">
<div class="card rounded shadow border-0">
<div class="card-body p-5 bg-white rounded">
<div class="table-responsive">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="mainAJAX.js"></script>
</body>
</html>
这是 mainAJAX.js 文件:
$(document).ready(function() {
$('#example').DataTable( {
// "ajax": "http://localhost:2121/arrays.txt"
"ajax": "https://www.rapidtech1898.com/aaadownload/arrays.txt"
} );
} );
有人告诉我 - 如果服务器也托管在同一个域(如 rapidtech1898.com)上,它可能会工作。但是,在将其部署到其他地方之前,有没有办法在本地测试这种想法?
解决方案
出于安全原因,这就是 CORS 的工作方式。除非服务器允许,否则您不能请求来自不同来源的数据。但是,出于开发目的,您可以通过多种方式禁用 CORS。这里有一篇很好的文章。但我个人最喜欢的是这个解决方案(使用不绕过 CORS 的代理):
fetch('https://cors-anywhere.herokuapp.com/https://www.rapidtech1898.com/aaadownload/arrays.txt', {
method: "GET",
headers: {
"Content-type": "application/json;charset=UTF-8",
"x-requested-with": "localhost:3000"
}
}).then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));
推荐阅读
- jquery - 查找为空的背景图像 url
- reactjs - React dropzone uploader with meteor 给出 error_upload 虽然图像预览看起来不错
- javascript - 如何添加 JSON 日期对象以禁用日期
- c++ - 使用 %s 的 C++ 嵌套循环
- azure - 关闭 Log Analytics 表架构的 Azure 警报
- python - 无法安装 NDK
- git - 我们可以复制 windows 文件系统来迁移 Git 服务器吗
- python - 如何让游戏重新开始?
- javascript - Axios (React Native) POST 请求适用于 iOS(模拟器)但不适用于 Android(模拟器)
- protractor - 量角器 - 是否可以使用单个“预期”语句对元素进行多次检查?