[英]Access-Control-Allow-Origin error on axios request even after enabling express CORS middleware
I am recently deployed my API on Heroku, and I'm having some CORS related issues.我最近在 Heroku 上部署了我的 API,我遇到了一些与 CORS 相关的问题。 I've seen many other posts that talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error:
Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
我已经看到许多其他关于启用 CORS 的帖子(我已经在我的代码中做到了),但是每当我发出 axios POST 请求时,我仍然会收到相同的错误:
Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
I've also tried messing around with the configuration object for cors(), but nothing seems to work.我也尝试过使用 cors() 的配置 object,但似乎没有任何效果。
The actual post request from the frontend looks like this:来自前端的实际发布请求如下所示:
const axiosConfig = {
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
},
};
await axios
.post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
.then((_) => Message.success("Successfully registered! 🎊"))
.catch((error) => Message.error(error.message));
and my app.js on the backend looks like this.我在后端的 app.js 看起来像这样。
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");
const app = express();
app.use(
cors({
allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
exposedHeaders: ["authorization"], // you can change the headers
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
})
);
// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");
const port = process.env.PORT || 8080;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
cb(null, "temp-storage/cover/");
} else {
cb(null, "temp-storage/");
}
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
},
});
const upload = multer({
// dest: "temp-storage/",
storage: storage,
limits: {
fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
},
});
// view engine setup
app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.json({ error: err.message });
});
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "build", "index.html"));
});
app.listen(port, console.log(`MyApp backend started on port ${port}!`));
module.exports = app;
I'd really appreciate it if someone could help me out!如果有人可以帮助我,我将不胜感激!
I generally use CORS module for cross origin requests how ever below code also works fine of you dont't want to add cors我通常使用 CORS 模块进行跨源请求,但是下面的代码也可以正常工作,您不想添加 cors
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin",*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
You can try adding this before adding your routes您可以在添加路线之前尝试添加它
// every response we send has these headers
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
You can try setting headers to allow as one of the answers suggest您可以尝试设置标题以允许作为答案之一
Access-Control-Allow-Origin: *
Or, you can use a middleware cors
package in node to do this.或者,您可以在节点中使用中间件
cors
package 来执行此操作。 CORS npm CORS npm
app.use(cors());
https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/ https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/
Or, you can use a proxy
from where you're requesting in the client-side like this:或者,您可以使用您在客户端请求的
proxy
,如下所示:
var proxy = https://cors-anywhere.herokuapp.com/;
await axios
.post(proxy+"https://myapp-backend.herokuapp.com/register", data, axiosConfig)
.then((_) => Message.success("Successfully registered! 🎊"))
.catch((error) => Message.error(error.message));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.