前端验证下跨域题目(npm验证)

[复制链接]
发表于 2025-6-4 08:15:45 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一、配景

在公司的开发中,有时候碰到前端接口请求非本域名下的接口,不处理的话,会存在跨域的题目,常见的解决办法有做nginx的署理转发,接口提供者的服务端做白名单等,另有一种是仅实用get请求的 jsonp的方式,本日我用js代码演示下跨域的情况
二、结果展示

关闭cros设置时的结果,存在跨域

三个按钮的链接依次是:
http://localhost:3000/api/test
http://localhost:4000/api/test
http://127.0.0.1:3000/api/test
三、代码展示


前端页面 (index.html)
后端服务器 (server.js)
差异端口的后端服务器 (server2.js)
3.1)index.html

是前端文件,路径是 public下面
代码如下
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>CORS 跨域测试</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             max-width: 800px;
  11.             margin: 0 auto;
  12.             padding: 20px;
  13.         }
  14.         .button-group {
  15.             margin: 20px 0;
  16.         }
  17.         button {
  18.             padding: 10px 20px;
  19.             margin: 5px;
  20.             cursor: pointer;
  21.             background-color: #4CAF50;
  22.             color: white;
  23.             border: none;
  24.             border-radius: 4px;
  25.         }
  26.         button:hover {
  27.             background-color: #45a049;
  28.         }
  29.         #result {
  30.             background-color: #f5f5f5;
  31.             padding: 15px;
  32.             border-radius: 4px;
  33.             white-space: pre-wrap;
  34.         }
  35.     </style>
  36. </head>
  37. <body>
  38.     <h1>CORS 跨域测试1</h1>
  39.     <div class="button-group">
  40.         <button onclick="testCors('http://localhost:3000/api/test')">测试同域名同端口</button>
  41.         <button onclick="testCors('http://localhost:4000/api/test')">测试同域名不同端口</button>
  42.         <button onclick="testCors('http://127.0.0.1:3000/api/test')">测试不同域名(127.0.0.1)</button>
  43.     </div>
  44.     <div id="result">结果将显示在这里...</div>
  45.     <script>
  46.         async function testCors(url) {
  47.             const resultDiv = document.getElementById('result');
  48.             resultDiv.textContent = `正在请求: ${url}\n`;
  49.             
  50.             try {
  51.                 const response = await fetch(url);
  52.                 const data = await response.text();
  53.                 resultDiv.textContent += `成功: ${data}`;
  54.             } catch (error) {
  55.                 resultDiv.textContent += `失败: ${error.message}`;
  56.             }
  57.         }
  58.     </script>
  59. </body>
  60. </html>
复制代码
3.2)package.json

  1. {
  2.   "name": "cors-demo",
  3.   "version": "1.0.0",
  4.   "description": "CORS demonstration with different scenarios",
  5.   "main": "server.js",
  6.   "scripts": {
  7.     "start": "node server.js",
  8.     "start2": "node server2.js"
  9.   },
  10.   "dependencies": {
  11.     "express": "^4.18.2",
  12.     "cors": "^2.8.5"
  13.   }
  14. }
复制代码
3.3) service.js

  1. const express = require('express');
  2. const cors = require('cors');
  3. const path = require('path');
  4. const app = express();
  5. // 提供静态文件服务
  6. app.use(express.static(path.join(__dirname, 'public')));
  7. // 启用 CORS
  8. // app.use(cors({
  9. //     origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
  10. //     methods: ['GET', 'POST'],
  11. //     credentials: true
  12. // }));
  13. app.get('/api/test', (req, res) => {
  14.     res.send(`Hello from server on port 3000! Request from: ${req.headers.origin}`);
  15. });
  16. const PORT = 3000;
  17. app.listen(PORT, () => {
  18.     console.log(`Server running on http://localhost:${PORT}`);
  19. });
复制代码
3.4)service2.js

  1. const express = require('express');
  2. const cors = require('cors');
  3. const app = express();
  4. // 启用 CORS
  5. // app.use(cors({
  6. //     origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
  7. //     methods: ['GET', 'POST'],
  8. //     credentials: true
  9. // }));
  10. app.get('/api/test', (req, res) => {
  11.     res.send(`Hello from server on port 4000! Request from: ${req.headers.origin}`);
  12. });
  13. const PORT = 4000;
  14. app.listen(PORT, () => {
  15.     console.log(`Server running on http://localhost:${PORT}`);
  16. });
复制代码
四、使用说明

4.1)安装依赖

  1. npm install
复制代码

4.2)启动服务器

打开两个终端窗口,分别运行:
  1. # 终端 1
  2. npm start    # 启动端口 3000 的服务器
  3. # 终端 2
  4. npm run start2    # 启动端口 4000 的服务器
复制代码
4.3)访问前端页面

使用浏览器打开 index.html 文件,你会看到三个按钮:
“测试同域名同端口”:请求 http://localhost:3000/api/test
“测试同域名差异端口”:请求 http://localhost:4000/api/test
“测试差异域名”:请求 http://127.0.0.1:3000/api/test
五、跨域解决方案说明

CORS 设置
在服务器端,我们使用了 cors 中间件来设置跨域访问:
  1. app.use(cors({
  2.     origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
  3.     methods: ['GET', 'POST'],
  4.     credentials: true
  5. }));
复制代码
其他跨域解决方案
除了 CORS,另有其他解决方案:
使用署理服务器
JSONP(仅支持 GET 请求)
使用 WebSocket
使用 postMessage 进行跨窗口通信
六、测试场景

同域名同端口
访问 http://localhost:3000/api/test
预期结果:成功,由于同源
同域名差异端口
访问 http://localhost:4000/api/test
预期结果:成功,由于设置了 CORS
差异域名
访问 http://127.0.0.1:3000/api/test
预期结果:成功,由于设置了 CORS
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表