Have an error with cors, if my cors is enable?

I want to do a request get or post to my firebase backend api

this is my request

const verify = async (address) => {
  const params = { address }
  const { data } = await client.get('test', { params })
}

and my backend i am using cors

const app = require('express')()
const cors = require('cors')

const options = {
  origin: true,
  methods: 'GET,POST,PUT,DELETE,OPTIONS,HEAD,PATCH',
  preflightContinue: false,
  optionsSuccessStatus: 204,
}

app.use(cors(options))

app.get('/test', (req, res) => {
  console.log('console.log', req.body)
  res.status(200).send('hello world!')
})

module.exports = {
  Module: () => app,
}

I don't know what happened, but I am getting an error in cors:

Access to XMLHttpRequest at 'https://...functions.net/test?address=AABB' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


Solution 1:

I suspect you need to insert the URL, on which your Vue App is running into options.origin

Or does options.origin: true set headers to '"Access-Control-Allow-Origin": *'?

EDIT: First, you need req.query.address in order to access the address query param, that you sent from Vue.

EDIT: Without setting your options to cors() I get the Access-Control-Allow-Origin: * Response Header from Express. Might not want to do this in production, but set origin to some URL that use the API.

const app = require('express')()
 const cors = require('cors')

app.use(cors())

app.get('/test', (req, res) => {
  console.log('console.log', req.query.address)
  res.status(200).send(`The address is ${req.query.address || "not existing"}`)
})


app.listen(3000, () => console.log("Express running..."))

enter image description here

Solution 2:

I use this. Find this solution on Stackoverflow :



//#region CORS - Area...
var whitelist = [
  "http://127.0.0.1:3000",
  "https://127.0.0.1:3000",
  "https://localhost:3000",
  "http://localhost:3000",
];
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      console.log("Blocked-Origin:", origin);
      callback(new Error("Not in CORS-Origin-List"));
    }
  },

  methods: ["POST, DELETE, GET"],
  optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
//#endregion CORS - Area...

And this solution is not recommended, but for Test ok...

app.use(
cors({
optionsSuccessStatus: 200,
credentials: true,
origin: "*",
 methods: ["GET", "POST", "DELETE"],
})
);

Note: origin: "*", not true