使用Express代理在jQuery DataTable调用API仍遇CORS及404错误求助
问题描述
客户确认已将localhost:3000加入API的CORS允许源列表,我无服务器权限。使用运行在localhost:3000的Express代理服务器请求该API,将数据加载到jQuery DataTable时,浏览器仍报CORS错误,还偶发404 Not Found。浏览器Network面板显示请求URL为http://127.0.0.1:3000/,状态码404。此前直接用jQuery调用测试API成功,代理配置后出现问题。注:stats.hostname.com为模拟API地址,后续将替换为真实地址。
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>
Express代理代码
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'); });
解决方案
1. 调整Express代理的路由顺序与匹配规则
当前代理中间件优先匹配所有请求(/),导致静态文件服务无法生效。需先处理静态文件,再设置代理,并缩小代理匹配路径,避免拦截静态页面请求:
const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); // 先处理静态文件,确保HTML页面正常访问 app.use(express.static('public')); // 仅代理以/api开头的请求,避免拦截根路径的静态页面 const apiProxy = createProxyMiddleware('/api', { target: 'https://stats.hostname.com', changeOrigin: true, // 若目标API路径不需要保留/api前缀,开启下面的配置 // pathRewrite: { '^/api': '' } }); app.use(apiProxy); app.listen(3000, () => { console.log('Proxy server listening on port 3000'); });
2. 确认静态文件目录结构
确保HTML文件放在public目录下,目录结构如下:
项目文件夹 ├── public/ │ └── index.html └── server.js (Express代码文件)
3. 验证请求路径
启动代理服务器后,访问http://localhost:3000/index.html,此时AJAX请求会发送到http://localhost:3000/api/stats/upwork_demo/?key=secret&date_from=2023-3-1&date_to=2023-4-1,代理会将其转发到目标API对应路径。
4. 排查CORS问题
若仍有CORS错误:
- 让客户再次确认API的CORS配置确实包含
http://localhost:3000(注意http/https协议差异,localhost与127.0.0.1为不同源) - 检查代理请求的响应头,确认
Access-Control-Allow-Origin是否正确返回
内容的提问来源于stack exchange,提问作者Fahad Hussain
相关产品推荐
相关产品推荐

