首页 > 解决方案 > 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}`);
});

提前致谢。

标签: javascriptexpresscorswebserver

解决方案


在您的智能手机上,来源是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 地址无关紧要,只有前端服务器的地址和主机。


推荐阅读