我的前端:8080和后端:8081運行在同一臺計算機上http://192.168.178.20。如果我http://localhost:8080在我的計算機上導航到一切正常(我可以成功地將請求發送到我的后端)。當我從智能手機導航到 時http://192.168.178.20:8080,前端將按預期顯示。但是我無法從智能手機向后端發送請求,它認為這與 cors 配置有關,但我無法弄清楚如何正確更改它。
我是否必須在后端以某種方式將我的智能手機列入白名單?當我想在生產中而不是在開發模式下運行它時,正確的配置看起來如何?
智能手機的私有 IP 地址(與計算機相同的網路)是192.168.178.21.
我當前的后端配置如下所示:
import cors from 'cors';
import express from 'express';
import cookieParser from 'cookie-parser';
const SERVER_PORT = 8081;
const app = express();
app.use(cors({
origin: ['http://localhost:8080'],
credentials: true
}));
app.use(express.urlencoded({
extended: true
}));
app.use(express.json());
app.use(cookieParser());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'x-access-token, Origin, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next();
});
// my routes ...
app.listen(SERVER_PORT, () => {
console.log(`Backend is listening on port ${SERVER_PORT}`);
});
提前致謝。
uj5u.com熱心網友回復:
從您的智能手機,來源是http://192.168.178.20:8080,但在您的 CORS 配置中,您只允許http://localhost:8080. 嘗試
app.use(cors({
origin: ['http://localhost:8080', 'http://192.168.178.20:8080'],
allowedHeaders: 'x-access-token',
methods: 'GET, POST, PUT, DELETE, OPTIONS',
credentials: true
}));
并洗掉顯式設定Access-Control-Allow-*標頭的(冗余)中間件。(Origin, Content-Type, Accept不需要設定為允許的標題,它們總是被允許的,除非你的意思是,例如Content-Type: application/json。)
客戶端(您的智能手機)的 IP 地址無關緊要,重要的是前端服務器的地址和主機。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/345558.html
標籤:javascript 表达 科尔斯 网络服务器
