javascript - cors vue 前端和 express 后端
问题描述
我的前端: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}`);
});
提前致谢。
解决方案
在您的智能手机上,来源是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 地址无关紧要,只有前端服务器的地址和主机。
推荐阅读
- python - cron 环境的问题
- python - 在 AWS 上使用 Tweepy 流式传输推文
- django - Django - 良好的数据库设计实践:辅助字段应该链接到基本用户模型还是员工模型?
- rest - 从 DocuSign Rest API 调用 getDocument 时如何使用加密
- javascript - React 组件在状态更改时不刷新内容 [Next.js]
- python - Why Python Mysql Query doesn't show all the columns whereas Phpmyadmin does it very well?
- javascript - 相同的函数在 javascript 中以不同的方式编写
- loops - How to write recursive nested loop in vue.js template?
- r - 如何删除每个月出现次数少于 n 的个体?
- java - 构建映像失败,尝试创建 docker 映像时未找到摘要错误