简体   繁体   中英

Why am I getting a CORS error in the browser but not in Postman?

I am using the Firebase emulators to serve Firebase functions on localhost. If I test my functions using Postman, this all works using the following request:

http://localhost:5001/project-XXXX/us-central1/api/users

Then, I fire up my Next.js application on port 3000 and try to use Axios to get the same data as follows:

  useEffect(() => {

    axios
      .get(
        "http://localhost:5001/project-XXXX/us-central1/api/users"
      )
      .then((res) => {
        console.log(res);
      })
      .catch(function (error) {
        console.log(error);
      });

  }, []);

However, now I'm getting a CORS error: "Access to XMLHttpRequest at 'http://localhost:5001/project-XXXX/us-central1/api/appointments/availability' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

In response to similar questions I have tried changing region and starting chrome with web-security disabled, which was both unsuccesful in solving the matter.

Does anyone have an idea as to why I am getting this error when requesting from the browser (and not from Postman)?

For full information, my index.js file of the Firebase cloud functions using Express.js:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

const express = require("express");
const cors = require("cors");

const authMiddleware = require("./authMiddleware");
const { user } = require("firebase-functions/v1/auth");

admin.initializeApp();
const app = express();

const { users, updateUser } = require("./routes/users");

// user-related routes
app.use("/users", users);

const api = functions.https.onRequest(app);

// export as Firebase functions
module.exports = { api: api, updateUser: updateUser };

Thanks jub0bs. My problem was solved by installing cors (npm install cors) and adding the following to my index:js:

const cors = require("cors");
app.use(cors());

This enables CORS for all origins, so only use for development and change before you go to production.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM