提问者:小点点

react API服务器上的cors


我已经为我的应用程序设置了一个开发和产品配置,并且需要在我的节点后端为两个特定的URL启用cors,因为它接受来自react前端的请求。我想把我的配置贴在这里,因为它花了相当多的谷歌来解决这个问题。希望这能节省一些时间。如果需要向cors策略中添加更多URL,只需扩展现有数组

反应节点(<)----&>

反应:

axios
    .get(API_URL + path, { withCredentials: true })
    .then((res) => {
      return res.data; // query succeeded
    })
    .catch(function (error) {
      console.log("Request Could Not Be Completed");
      return false; //query failed
    });
  return query;
}; 

node.(server.js)

var allowedOrigins = ["https://api.example.com", "http://localhost:3000"];
const corsOptions = {
  origin: function (origin, callback) {
   
    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);
    }
    console.log(allowedOrigins.indexOf(origin));
    return callback(null, true);
  },
  credentials: true
};

app.use(cors(corsOptions));

共1个答案

匿名用户

希望这能节省一些时间!