从 DataTable 中的 API 获取数据时出现 CORS Origin 错误

问题描述 投票:0回答:0

我有一个 API 接受在其允许的 CORS 来源列表中添加了 localhost:3000。

我没有访问服务器的权限,但添加了客户端提到的“localhost:3000”。

现在我正在尝试使用 express/node 向该 API 发出请求,并将其加载到 Jquery DataTable 中,代理服务器在 localhost:3000 上运行,但仍然在浏览器上收到 CORS 错误。

HTML/Jquery代码:

<!DOCTYPE html>
<html>

<head>
    <title>API Demo</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>

<body>
    <table id="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Visits</th>
                <th>Pageviews</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: 'api/stats/upwork_demo/?key=secret&date_from=2023-3-1&date_to=2023-4-1',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    // Initialize DataTables
                    $('#table').DataTable({
                        data: data.data,
                        columns: [
                            { title: 'Date', data: 'date' },
                            { title: 'Visits', data: 'visits' },
                            { title: 'Pageviews', data: 'pageviews' }
                        ]
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('Error: ' + textStatus + ' - ' + errorThrown);
                }
            });
        });
    </script>
</body>

</html>

快递编码:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// Proxy middleware
const apiProxy = createProxyMiddleware('/', {
  target: 'https://stats.hostname.com',
  changeOrigin: true,
});

app.use(apiProxy);

// Serve static files
app.use(express.static('public'));

// Start server
app.listen(3000, () => {
  console.log('Proxy server listening on port 3000');
});

我真的很陌生。这是我的浏览器网络->标题选项卡说的

请求网址:http://127.0.0.1:3000/ 请求方式:GET 状态代码:404 未找到 远程地址:127.0.0.1:3000 推荐人政策:严格起源时交叉来源

有时它也会抛出 CORS 错误。

基本上我只想加载数据。我能够使用另一个测试 API 在简单的 javascript/jquery 中成功地做到这一点,但是当客户给我这个时,它有这个 CORS 限制,据我所知,我现在必须通过代理服务器来做到这一点,这导致了我各种各样的问题.

BTW stats.hostname.com 是一个虚拟 API。稍后我会用原来的替换它。

真的很感激任何帮助,谢谢。

express datatable cors http-status-code-404
© www.soinside.com 2019 - 2024. All rights reserved.