【问题标题】:CORS policy Error after deploy Front to firebae back to heroku将Front部署到firebae回到heroku后CORS策略错误
【发布时间】:2021-02-20 14:59:28
【问题描述】:

我们正在尝试我和我的朋友部署一个在本地完全运行的项目。

但现在我们部署了它(前面到 firebase,后面到 heroku), 现在每个请求我们都得到了 cors 政策

app.use(cors());

var allowCrossDomain = function (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"
  );

  // intercept OPTIONS method
  if ("OPTIONS" == req.method) {
    res.send(200);
  } else {
    next();
  }
};

app.use(allowCrossDomain);

app.use(bodyParser.json());

app.use("/function", couponRoutes);

mongoose
  .connect(  `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.qvs4c.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
  )
  .then(() => {
    app.listen(5000);
  })
  .catch((err) => {
    console.log(err);
  });

这是后面的代码(我也尝试过不使用 allowcross 域),但没有任何效果。

我们正在做前面的常规 axios 请求,它不起作用,希望得到帮助。

【问题讨论】:

    标签: reactjs express deployment cors mern


    【解决方案1】:

    你必须通过传递一个 javascript 对象来配置 cors 来配置它,如下所示

    const corsOptions = {
    "origin": "*",
      "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
      "preflightContinue": false,
      "optionsSuccessStatus": 200
      "exposedHeaders": ['Content-Length', 'X-Requested-With', ' Authorization','Content-Type'],
    }
    
    app.use(cors(corsOptions))
    

    你应该使用它而不是你的代码来让 cors 工作

    如果您有多个来源,请使用以下 sn-p

    var allowedOrigins = ['http://localhost:3000',
                          'http://yourapp.com'];
    app.use(cors({
      origin: function(origin, callback){
        // allow requests with no origin 
        // (like mobile apps or curl requests)
        if(!origin) return callback(null, true);
        if(allowedOrigins.indexOf(origin) === -1){
          var msg = 'The CORS policy for this site does not ' +
                    'allow access from the specified Origin.';
          return callback(new Error(msg), false);
        }
        return callback(null, true);
      }
    }));
    

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2018-07-16
      • 2016-06-27
      • 2012-05-22
      • 2014-05-18
      • 2016-12-27
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多