Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular CORS request blocked

I am trying to connect my Angular app with a simple REST server on express. The server only sends json data in reply to request. To add CORS support, I used the cors module from npm. On the Angular app, I added HttpHeaders following the instructions from this question: Angular CORS request blocked.

Here is my code in express where I set up the cors Options: `

// async CORS setup delegation
function corsOptsDelegator(req, cb) {
    let opts = {},
        origin = req.header('Origin');
    if(imports.allowedOrigins.indexOf(origin) === 1) opts.origin = true;
    else opts.origin = false;
    opts.optionsSuccessStatus = 200;
    opts.methods = ['POST', 'GET']; // allowed methods
    opts.credentials = true; // for passing/setting cookie 
    opts.allowedHeaders = ['Content-Type', 'Accept', 'Access-Control-Allow-Origin']; // restrict headers 
    opts.exposedHeaders = ['Accept', 'Content-Type']; // for exposing custom headers to clients; use for hash
    cb(null, opts);
}
`

Here's how I added it to the global get handler:

`
app.get('/', cors(corsOptsDelegator), (res, req, nxt) => {
    // only for adding cors on all requests
    nxt();
});
`

Here's how I set up the Angular service:

`

export class ContentGetterService {

  private root: string;
  private corsHeaders: HttpHeaders;
  //private contents: string;

  constructor(private http: HttpClient) {
    this.root = 'http://localhost:8888';
    this.corsHeaders = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:4200'
    });
    //this.contents = '';
   }

  getContent(subs: Array<string>): Observable<IContent> {
    return (() => {
      return this.http.get<IContent>( (() => {
        let r = this.root;
        subs.forEach((s, i, a) => {
          if(i === a.length-1) {
            r += s;
          }
          else {
            if(s !== '/') {
              r += s;
            }
          }
        });
        return r;
      })(), {
        headers: this.corsHeaders
      });

    })();
  }
  }

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

Thanks.

like image 626
Abrar Hossain Avatar asked May 08 '18 16:05

Abrar Hossain


1 Answers

In case you are using angular-cli, you can use a proxy:

proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:8888",
    "secure": false
  }
}

Will redirect all requests with /api prefix to localhost:8888 without any cors issue.

Offical docs: https://angular.io/guide/build#proxying-to-a-backend-server

like image 160
TheUnreal Avatar answered Oct 09 '22 17:10

TheUnreal