gpt4 book ai didi

javascript - 即使在启用 express CORS 中间件后,axios 请求上的 Access-Control-Allow-Origin 错误

转载 作者:行者123 更新时间:2023-12-02 09:02:40 25 4
gpt4 key购买 nike

我最近在 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;

如果有人可以帮助我,我将不胜感激!

最佳答案

我通常将 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();
});

关于javascript - 即使在启用 express CORS 中间件后,axios 请求上的 Access-Control-Allow-Origin 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62116134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com