Ansh Godha
Ansh Godha

Reputation: 21

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. 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. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

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.

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!

Upvotes: 1

Views: 1606

Answers (3)

Anil
Anil

Reputation: 29

I generally use CORS module for cross origin requests how ever below code also works fine of you dont't want to add 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();
});

Upvotes: 2

ABGR
ABGR

Reputation: 5205

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 npm

app.use(cors());

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:

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));

Upvotes: 1

KaranManral
KaranManral

Reputation: 694

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();
});

Upvotes: 1

Related Questions