8

CORS is fine on server and works as intended. I tried sending requests to my server's REST API with the angular HTTPClient and I receive a CORS error. Why is this an error if CORS is enabled on the server? Shouldn't it be fine on the client?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/blah/blah (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

How can I enable CORS on this request please..... enter image description here

Jeff
  • 170
  • 2
  • 5
  • 19
scott
  • 1,531
  • 2
  • 16
  • 29
  • 2
    You don't enable cors client side in angular. I would double check the order of your middleware and ensure it is running before the request is being made. Meaning, before the route is defined. – David Anthony Acosta Aug 01 '18 at 18:42
  • Thanks kindly David – scott Aug 02 '18 at 06:25
  • Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – Heretic Monkey Apr 03 '19 at 12:30
  • This answer maybe useful: https://stackoverflow.com/a/58064366/7059557 – AmirReza-Farahlagha Sep 23 '19 at 14:12

3 Answers3

4

For future refrence it was "Davids" answer that assisted me, the cors was not added before all routing.

"..... Meaning, before the route is defined." so right after ... var app = express();

I just use... app.use(cors());

scott
  • 1,531
  • 2
  • 16
  • 29
3

A little intro:

Cross-Origin Resource Sharing aka CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin (e.g. http://localhost:3000), access to selected resources from a different origin (e.g. http://localhost:8080). In other words, a web app executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.

The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS.


How to Fix CORS Issues?

You can do it yourself by creating an Express middleware. Here's the appropriate code snippet:

// Enable CORS for specific origins:


app.use((req, res, next) => {
  // Allow multiple predefined origins
  const allowedOrigins = ["https://deployed-app.com", "http://localhost:3000"];
  const origin = req.headers.origin; // extract the origin from the header
  if (allowedOrigins.indexOf(origin) > -1) { // if the origin is present in our array   
    res.setHeader("Access-Control-Allow-Origin", origin); // set the CORS header on the response
  }
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next(); // move on to the next middleware
});

Alternatively, you can accept all requests, but this option is only appropriate if you're in development or if your API is public :)

 app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    next();
 });

Additionally, there's an Express CORS middleware and this is how you would use it:

npm install cors --save

Enable All CORS Requests:

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

    app.use(cors());

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

    const port = process.env.PORT || 8080;

    app.listen(port, () => {
     console.log(`CORS-enabled server is up on ${port}`);
   });

Enable CORS for a Single Route

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

    app.get('/products/:id', cors(), (req, res, next) => {
      res.json({msg: 'This is CORS-enabled for a Single Route'})
    });

     const port = process.env.PORT || 8080;

       app.listen(port, () => {
         console.log(`CORS-enabled server is up on ${port}`);
       });

Important gotcha: When it comes to Express middleware, the order is very important. So make sure CORS is enabled before any other controller/ route/ middleware which may depend on it.

Dženis H.
  • 7,284
  • 3
  • 25
  • 44
2

You dont need to enable cors in angular, this is a server side issue. See:

https://stackoverflow.com/a/29548846/4461537

René Winkler
  • 6,508
  • 7
  • 42
  • 69