Only certain cross origin requests working using npm cors()

app.use(cors()) not working
no 'access-control-allow-origin' header is present on the requested resource.
what is cors
cross-origin request blocked
express cors multiple origins
access-control-allow-origin localhost
enable cors node http server
allow cross origin request express

I'm building a website using react(it runs on localhost:3000), that gets its user info from an API I built that runs on localhost:4000. To allow requests between the two I was told to use the npm cors package to allow cross-origin requests back and forth. I have set up cors in my API as follows: app.use(cors({credentials: true, origin: true}));

In my react app I have been using axios in order to send get and post requests, I have one such get request in a component that does receive a response:

isLoggedIn(){
        let isLogged = false;
        Fetch("http://localhost:4000/IsLogged")
        .then((results)=> {
            console.log(results)
            isLogged = results.data
        })
        .catch((err)   => console.log(err))
        this.setState({loggedIn: isLogged})
    }
    componentDidMount(){
        this.isLoggedIn();
    }

However, When I try receive the user details using this code:

getUserDetails(){
    Fetch("http://localhost:4000/userDetails")
        .then((results)=> {console.log(results)})
        .catch((err)   => console.log(err))
  }
  componentDidMount(){
    this.getUserDetails()
  }

I get this response in the console:

Access to XMLHttpRequest at 'http://localhost:3000/login' (redirected from 'http://localhost:4000/userDetails') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the server side code:

app.get("/userDetails",(req,res)=>{
  //if there is no userID associated with the session then the user hasnt logged in, redirect to login
  console.log(req.session.UserID)
  if(!req.session.UserID) {
    res.redirect("http://localhost:3000/login")
  }else{
    let userID = req.session.UserID
    connection.query("SELECT * FROM `users` WHERE id =" + userID)
    .then((rows) => res.send(rows[0]))
    .catch((err) => console.error(err))
  }
})

It's probably something stupid, so I apologize if this is really basic, any reading links on this also would be great. Thanks for any help given!

This is not CORS thing.

You can not redirect from the back-end. In other words if the user did not logged in your api should return a Not-authorized response. Then at your front end you should route to the login page.

The problem is your are trying to access localhost:3000 (front-end) from the back-end. And the cors is setup for port 4000 or the backend.

 console.log(req.session.UserID)
 if(!req.session.UserID) {
     //Your should return unauthorized response then check the response at the front end react axios response.
       res.json({
         status: 401,
         message: "Action Not Allowed",
         name: "AUTHORIZATION_ERROR"
       });
     //res.redirect("http://localhost:3000/login")
  }else{ ....


getUserDetails(){
Fetch("http://localhost:4000/userDetails")
    .then((results)=> {
        if(results.data.status == 401) {
              // then change the page.
         }
     })
    .catch((err)   => console.log(err))
}

Express cors middleware, This is a Node.js module available through the npm registry. function (req, res, next) { res.json({msg: 'This is CORS-enabled for only example.com. Certain CORS requests are considered 'complex' and require an initial OPTIONS request (called the origin : Configures the Access-Control-Allow-Origin CORS header. The CORS middleware can be configured to accept only specific origins and headers. It's a good idea for security reasons to be restrictive by default. As an example of how to do this, you can reconfigure the CORS middleware to only accept requests from the origin that the frontend is running on.

In your file where you have app.use(cors({credentials: true, origin: true})); try to add this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

And then in your routes, pass the next, like this:

app.get("/userDetails",(req,res,next)=>{
  //if there is no userID associated with the session then the user hasnt logged in, redirect to login
  console.log(req.session.UserID)
  if(!req.session.UserID) {
    res.redirect("http://localhost:3000/login")
  }else{
    let userID = req.session.UserID
    connection.query("SELECT * FROM `users` WHERE id =" + userID)
    .then((rows) => res.send(rows[0]))
    .catch((err) => console.error(err))
  }
})

Let me know if it worked! P.S - Which server side handling are you using? Provide so we can help you better!

Handling CORS in Express, How to allow cross site requests by setting up CORS. usually only access HTTP resources from the same domain (origin) that serves Loading images or scripts/styles from the same origin always works. If you are using Node.js and Express as a framework, use the CORS Allow only specific origins. Enabling CORS Pre-Flight. Certain CORS requests are considered 'complex' and require an initial OPTIONS request (called the "pre-flight request"). An example of a 'complex' CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers.

You can use below middleware in your node server to modify incoming requests. just place this before your routs and it will do the trick..

app.use(function(req, res, next) {
  // Website you wish to allow to connect
  res.setHeader("Access-Control-Allow-Origin", "*");
  // Request methods you wish to allow
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  // Request headers you wish to allow
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type"
  );
  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader("Access-Control-Allow-Credentials", true);
  // Pass to next layer of middleware
  next();
});

cors, Node.js CORS middleware. Pull Requests. 0. Homepage. github.com/ expressjs/cors#readme. Repository. github.com/expressjs/cors� Well, For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, if you want to access your API hosted at https://api.github.com from your client-side frontend application which is hosted at https://example.com. The browser will not allow this request to complete. You only need to think about CORS when :

What is CORS? Complete Tutorial on Cross-Origin Resource Sharing, The application you're going to work with was Therefore, it constitutes a cross- origin request and is Note: The call using curl works just fine, as CORS only Notice that some custom middleware is and modify the callApi() function so that it sends a� Cross-origin resource sharing (CORS) allows AJAX requests to skip the Same-origin policy and access resources from remote hosts. In this post I will show you how to enable CORS support in Express.

Using CORS in Express. Cross-origin resource sharing (CORS , Cross-origin resource sharing (CORS) allows AJAX requests to skip the I will also provide some tips to handle common use cases that come up when The easiest way to get CORS working in Express is by using the cors npm module. By default, only 6 response headers are exposed over CORS:. The /echo and controller endpoints allow cross-origin requests using the specified policy. The /echo2 and Razor Pages endpoints do not allow cross-origin requests because no default policy was specified. The [DisableCors] attribute does not disable CORS that has been enabled by endpoint routing with RequireCors.

Cross-Origin Resource Sharing (CORS), This means that a web application using those APIs can only request resources from the same origin Images/video frames drawn to a canvas using drawImage () . The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let Some requests don't trigger a CORS preflight. I'm trying to build a web server in node.js that will support cross-domain scripting, while still providing static files from a public directory. I'm using the express.js and am not really sure how

Comments
  • Why does the error message say, "at http://localhost:3000/login (redirected from http://localhost:4000/userDetails)" - what business would your API running on port 4000 have redirecting to the frontend on port 3000 to begin with …?
  • It's just checking to see if you're trying to access the user dashboard without having logged in if you type localhost:4000/userDetails if you haven't, redirect to the login page
  • You said this was an API, why would anyone try to access a user dashboard by calling an API URL? If any of your :4000 URLs get called without the proper credentials, your API should deal with that by issuing an appropriate error code, not by redirecting to the frontend! You are mixing two different things here in a way that makes little sense.
  • no I added all that in and restarted the server and still no luck!
  • Which server side handling are you using?
  • I'm using Express.js is the package I'm using to handle my HTTP requests
  • @MiguelCruz Man, that was not a cors issue at all.
  • Yes i can see that. You're totally right. I didn't pay attention to the port. he just gotta use the 4000 instead of the 3000. But i'll leave my answer in case anyone have a cors problem.
  • I tried your snippet too and it didn't work, I appreciate the comments!