为什么cors错误存在,甚至与添加响应头托管heroku服务器

7hiiyaii  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(156)

我创建了一个全栈MERN应用程序,并在heroku上托管了一个服务器。当使用托管的URL时,我一直收到CORS错误,阻止我的前端访问我的API:
CORS策略已阻止从源“http://localhost:3000”访问位于“https://perf2-api.herokuapp.com/oils/6411f65e4ed9306f3e4921bf”的XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我已经搜索了互联网在这一点上,包括这个网站和种在我的智慧。没有解决方案已经工作。我使用cors在本地的服务器端口,我没有问题(http://localhost:8082/)
主要是唯一一个我见过但没有尝试过的涉及到在Heroku上创建我自己的代理,但我有点困惑如何做到这一点,并怀疑这是否是必要的
有没有人遇到过这种情况,或者有解决办法?”
我见过的大多数解决方案都涉及以不同的方式使用响应头,我在代码中尝试了不同的组合,基本上我见过的所有方法。下面是一些例子:
1.

app.listen(port, () => console.log(`Server is running on port 
     ${port}`));

     app.get("/", (req, res, next) => {
     res.header("Access-Control-Allow-Origin", "http://perf2- 
    api.herokuapp.com/");
    res.header("Access-Control-Allow-Credentials", true);
    if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "POST, PUT, PATCH, 
     GET, DELETE");
    return res.status(200).json({});
    }

     res.sendStatus(200);
   });
app.all('*', function (req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      next();
     });
app.options('/*', (req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 
   'GET,PUT,POST,DELETE,OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Content-Type, 
   Authorization,            
         Content-Length, X-Requested-With');
        res.sendStatus(200);
      });

以下是我当前的server.js文件导入和中间件

const path = require("path");
  const express = require("express");
  const bodyParser = require("body-parser");
  const logger = require("morgan");
  const cors = require("cors");
  const app = express();
  const publicPath = path.join(__dirname, 
  "frontend/perfumery2_client/build");
  const oilRoutes = require("./routes/api/oils");
  const connectDB = require("./config/db");

  const corsOptions = {
    credentials: true,
    origin: "*"
   }

     app.use((req, res, next) => {
     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Origin", "*");
     res.header(
     "Access-Control-Allow-Headers",
     "Origin, X-Requested-With, Content-Type, Accept"
    );
    res.header("Access-Control-Allow-Methods", "POST, PUT, PATCH, 
   GET, DELETE");
    if (req.method === "OPTIONS" || "OPTIONS" === req.method) {
   return res.status(200).json({});
   }
   next();
  });

主要是唯一一个我见过但没有尝试过的涉及到在Heroku上创建我自己的代理,但我有点困惑如何做到这一点,并怀疑这是否是必要的
有没有人遇到过这种情况,或者有解决办法?”

3npbholx

3npbholx1#

您可以尝试npm cors package作为中间件,而不是您的自定义中间件。CORS包允许您进行多次配置,并且非常易于使用。

import cors from 'cors';
import express from 'express';

const app = express()
app.use(cors()); // <---- use cors middleware

相关问题