【问题标题】:cors vue frontend and express backendcors vue 前端和 express 后端
【发布时间】:2021-12-15 05:22:54
【问题描述】:

我的前端 :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}`);
});

提前致谢。

【问题讨论】:

    标签: javascript express cors webserver


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-12
      • 2019-03-11
      • 2020-05-24
      • 2019-11-06
      • 2020-12-03
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      相关资源
      最近更新 更多