Ad

How To Fix CORS Node.js On Google App Engine

- 1 answer

I have 2 applications deployed on Google App Engine;

A is a Angular 8 application.

B is a Node.js express application.

Whenever I try to call an API in my backend I receive this error:

Access to XMLHttpRequest at '"APPLICATION B"/getGroups?userKey=' from origin 'APPLICATION A' 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.

I made sure to enable APPLICATION A url in google app engine credentials of APPLICATION B as an Authorized Javascript Origin and Authorized Redirect URI. In localhost everything works.

What I tried on App.js:

ATTEMPT 1

app.use(function (req, res, next) {
res.header(“Access-Control-Allow-Origin”, “*”);
res.header(“Access-Control-Allow-Methods”, “GET,HEAD,OPTIONS,POST,PUT”);
res.header(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization”);
next();
});

ATTEMPT 2

var cors = require('cors')
app.use(cors())

ATTEMPT 3

var cors = require('cors')

var corsOptions = {
  origin: 'APPLICATION A',
}

app.use(cors(corsOptions ));
app.options('*', cors());

This is the GET I do in my angular 8 application A

  getGroupsRequest(id): Observable<any> {
    const url = "APPLICATION B"
    return this.http.get(url + id);
  }

If I use a CORS plugin or open google chrome "--disable-web-security" it works.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Users\510919\ChromeDev" --disable-web-security --auto-open-devtools-for-tabs
Ad

Answer

Try this in your app.js in your Node.js file

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

var originsWhitelist = [
  '<FRONT-END URL>',     
   'http://www.myproductionurl.com'
];
var corsOptions = {
  origin: function(origin, callback){
        var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
        callback(null, isWhitelisted);
  },
  credentials:true
}

app.use(cors(corsOptions));

This will enable on your Node.js

Now you will need to prepare your Angular app to support CORS

To enable CORS you can extend the BrowserXhr and include that in the bootstrapping process. Create a file in your Angular application project named cust-ext-browser-xhr.ts and paste the following code:

import {Injectable} from "@angular/core";
import {BrowserXhr} from "@angular/http";
@Injectable()

export class CustExtBrowserXhr extends BrowserXhr {
  constructor() {
      super();
  }
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = true; 
    return <any>(xhr);
  }
}

And in order to use your Custom BrowserXhr you will need to do something like this.

import { provide } from '@angular/core';
import { AppComponent} from './app/';
import { BrowserXhr } from '@angular/http';
import {CustExtBrowserXhr} from './app/path-to-file/cust-ext-browser-xhr';
@NgModule({
  imports: [
    HttpModule,
    BrowserModule,
    …
  ],
  declarations: [AppComponent],
  providers: [
    {provide: BrowserXhr, useClass:CustExtBrowserXhr},
    {provide: LocationStrategy, useClass: HashLocationStrategy}
    …
  ],
  bootstrap: [ AppComponent ]
})

Hope it helps you.

Ad
source: stackoverflow.com
Ad