問題:Access to fetch at 'http://localhost:3000/save' from origin 'http://localhost:5174' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.。
分析:CORS (跨域請求) 被攔截?——?http://localhost:5174
請求 http://localhost:3000
,但 Access-Control-Allow-Origin
頭部沒有配置,導致請求被瀏覽器攔截。
?解決:前端可以嘗試進行跨域請求。
①修改后端
(假設是 Express): 在 server.js
(或 index.js
)中添加:
// 記得ctrl+shift+y打開終端,在里頭運行 npm install cors
const cors = require("cors");
app.use(cors());
(假設包管理中的? "type": "module")
// 記得ctrl+shift+y打開終端,在里頭運行 npm install cors
import cors from 'cors';
app.use(cors());
根據情況,是? express服務器?還是 "type": "module",判斷是用require還是import
②手動設置響應頭:
app.use((req, res, next) => {res.header('Access-Control-Allow-Origin', 'http://localhost:5174');res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');if (req.method === 'OPTIONS') {return res.status(200).end();}next();});
?或者
app.use((req, res, next) => {res.header("Access-Control-Allow-Origin", "*"); // 或指定特定前端地址res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");next();
});
?③如果后端無法修改,可以在 fetch
請求中加入 mode: "cors"
:
const response = await fetch("http://localhost:3000/save", {method: "POST",mode: "cors", // 添加 CORS 模式headers: {"Content-Type": "application/json"},body: JSON.stringify({ content: text })
});
完整代碼:
import cors from 'cors';
import express from 'express';const app = express();
const PORT = 3000; // 后端服務器端口// 允許跨域請求
app.use(cors({origin: 'http://localhost:5174', // 允許的前端域名methods: ['GET', 'POST'], // 允許的請求方法allowedHeaders: ['Content-Type', 'Authorization'], // 允許的請求頭
})); // 額外的跨域處理
app.use((req, res, next) => {res.header('Access-Control-Allow-Origin', 'http://localhost:5174');res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');if (req.method === 'OPTIONS') {return res.status(200).end();}next();});app.use(express.json()); // 解析JSON請求體// 添加 get請求,檢查后端是否正常運行
app.get('/', (req, res) => {res.send('√后端運行正常!');
});
注: 注意順序,press和cors的順序
?