我最近在 Heroku 上部署了我的 API,但我遇到了一些与 CORS 相关的问题。我已经看到许多其他关于启用 CORS 的帖子(我已经在我的代码中这样做了),但是每当我发出 axios POST 请求时,我仍然遇到相同的错误:Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
我也尝试弄乱配置cors() 的对象,但似乎没有任何效果。
来自前端的实际发布请求如下所示:
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));
我在后端的 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;
如果有人可以帮助我,我将不胜感激!