欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端驗證下跨域問題解決方案(npm驗證)

 更新時間:2025年07月10日 10:15:14   作者:打破砂鍋問到底007  
npm是Node.js的包管理工具,用于下載、刪除和更新包,這篇文章主要介紹了前端驗證下跨域問題解決方案(npm驗證)的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

一、背景

在公司的開發(fā)中,有時候遇到前端接口請求非本域名下的接口,不處理的話,會存在跨域的問題,常見的解決辦法有做nginx的代理轉(zhuǎn)發(fā),接口提供者的服務端做白名單等,還有一種是僅適用get請求的 jsonp的方式,今天我用js代碼演示下跨域的情況

二、效果展示

關(guān)閉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下面

代碼如下

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS 跨域測試</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .button-group {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        #result {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <h1>CORS 跨域測試1</h1>
    <div class="button-group">
        <button onclick="testCors('http://localhost:3000/api/test')">測試同域名同端口</button>
        <button onclick="testCors('http://localhost:4000/api/test')">測試同域名不同端口</button>
        <button onclick="testCors('http://127.0.0.1:3000/api/test')">測試不同域名(127.0.0.1)</button>
    </div>
    <div id="result">結(jié)果將顯示在這里...</div>

    <script>
        async function testCors(url) {
            const resultDiv = document.getElementById('result');
            resultDiv.textContent = `正在請求: ${url}\n`;
            
            try {
                const response = await fetch(url);
                const data = await response.text();
                resultDiv.textContent += `成功: ${data}`;
            } catch (error) {
                resultDiv.textContent += `失敗: ${error.message}`;
            }
        }
    </script>
</body>
</html> 

3.2)package.json

{
  "name": "cors-demo",
  "version": "1.0.0",
  "description": "CORS demonstration with different scenarios",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "start2": "node server2.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "cors": "^2.8.5"
  }
}

3.3) service.js

const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();

// 提供靜態(tài)文件服務
app.use(express.static(path.join(__dirname, 'public')));

// 啟用 CORS
// app.use(cors({
//     origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
//     methods: ['GET', 'POST'],
//     credentials: true
// }));

app.get('/api/test', (req, res) => {
    res.send(`Hello from server on port 3000! Request from: ${req.headers.origin}`);
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
}); 

3.4)service2.js

const express = require('express');
const cors = require('cors');
const app = express();

// 啟用 CORS
// app.use(cors({
//     origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
//     methods: ['GET', 'POST'],
//     credentials: true
// }));

app.get('/api/test', (req, res) => {
    res.send(`Hello from server on port 4000! Request from: ${req.headers.origin}`);
});

const PORT = 4000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
}); 

四、使用說明

4.1)安裝依賴

npm install

4.2)啟動服務器

打開兩個終端窗口,分別運行:

# 終端 1
npm start    # 啟動端口 3000 的服務器

# 終端 2
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 中間件來配置跨域訪問:

app.use(cors({
    origin: ['http://localhost:3000', 'http://localhost:4000', 'http://127.0.0.1:3000'],
    methods: ['GET', 'POST'],
    credentials: true
}));

其他跨域解決方案

除了 CORS,還有其他解決方案:

使用代理服務器

JSONP(僅支持 GET 請求)

使用 WebSocket

使用 postMessage 進行跨窗口通信

六、測試場景

同域名同端口

訪問 http://localhost:3000/api/test

預期結(jié)果:成功,因為同源

同域名不同端口

訪問 http://localhost:4000/api/test

預期結(jié)果:成功,因為配置了 CORS

不同域名

訪問 http://127.0.0.1:3000/api/test

預期結(jié)果:成功,因為配置了 CORS

總結(jié)

到此這篇關(guān)于前端驗證下跨域問題解決方案(npm驗證)的文章就介紹到這了,更多相關(guān)前端驗證下跨域問題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論