Home > Mobile >  When I deploy my website, client post/get requests blocked by CORS
When I deploy my website, client post/get requests blocked by CORS

Time:11-18

Using NodeJS as backend and React as frontend. Frontend uses axios to do post/get requests. Everything is working well in development with localhost:5000 as server and localhost:3000 as client.

However, when I deploy my server and client to websites, they fail to work. I have changed the respective localhost addresses to the website's address but to no avail. Here is how I set my backend code:

const server = express();
server.use(cors({origin: "https://frontendwebsitename.com", credentials: true}));

server.use(express.json());
server.use(express.urlencoded({extended:true}))

In my frontend website console, I get this error: Access to XMLHttpRequest at 'https://backendwebsitename.herokuapp.com/fetchDefaultSearch' from origin 'https://frontendwebsitename.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any ideas?

CodePudding user response:

You have to implement one to two things For backend use node package for CORS 'npm install cors' and add this to your App configuration https://expressjs.com/en/resources/middleware/cors.html

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

And now you need to verify is your Front-End bucket enabled settings for CORS if yes then it will work if not you need to enable that as well. https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html

CodePudding user response:

Also, suggest using Configuring CORS Asynchronously

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

var allowlist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (allowlist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  } else {
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}

app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
  • Related