Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable Access-Control-Allow-Origin for angular 5/nodejs?

Read many ways for including of 'Access-Control-Allow-Origin' and none worked for me.

I use @angular/common/http module and external url as data source. by the attempt to get data instead, get error: /////.................

Failed to load http://accounts.......com/accounts: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 503.


account.service.ts:

import { Injectable                    } from '@angular/core';
import { Router                        } from '@angular/router';
import { HttpClient, HttpParams        } from '@angular/common/http';
import { HttpHeaders                   } from '@angular/common/http';

import { Observable                    } from 'rxjs';
import { catchError                    } from 'rxjs/operators';

import { Account                       } from '../models/account';

const baseUrl     : string = 'http://accounts..................com/';
const httpOptions : any    = {
  headers: new HttpHeaders({
    //'Content-Type':  'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Allow-Origin': '*'
  })
};

@Injectable()
export class AccountService {
  private isUserLoggedIn;
  private usreName;
  private account : Account;

  constructor(
    private http: HttpClient,
    private router: Router
  ) {}

  logIn (credentials: any): Observable<Account> {
    return this.http.get<Account>(baseUrl + 'accounts');
  }
}

app.module.ts

import { BrowserModule                 } from '@angular/platform-browser';
import { HttpClientModule              } from '@angular/common/http';
import { NgModule                      } from '@angular/core';

import { routing                       } from './routing';
import { AppComponent                  } from './app.component';
import { AppGlobal                     } from './app.global';

import { AccountComponent              } from './components/account/account.component';

@NgModule({
  declarations  : [
    AppComponent,
    AccountComponent,
    ....
  ],
  imports       : [
    routing,
    BrowserModule,
    HttpClientModule,
    CookieModule.forRoot()
  ],
  providers     : [AccountService, AppGlobal],
  bootstrap     : [AppComponent]
})
export class AppModule { }

Help please

////////////////Tried fix 1

//......
import { HttpHeaders} from '@angular/common/http';
//.......
logIn (credentials: any): Observable<Account> {

    const headers = new HttpHeaders()
      .append('Content-Type', 'application/json')
      .append('Access-Control-Allow-Headers', 'Content-Type')
      .append('Access-Control-Allow-Methods', 'GET')
      .append('Access-Control-Allow-Origin', '*');
    return this.http.get<Account>(baseUrl + 'accounts',  {headers});
}
enter image description here

I am still getting that error :

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 503.

////////////////Tried fix 2

proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:4200",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

ng serve --proxy-config proxy.conf.json

also error

like image 240
aaaaaaaaax10 Avatar asked May 30 '18 14:05

aaaaaaaaax10


1 Answers

**Set headers to allow CORS origin in Express **

=> Add code in the server.js file or mail file.

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();
 });

CORS (Cross-Origin Resource Sharing) is an HTML5 feature that allows one site to access another site’s resources despite being under different domain names.

The W3C specification for CORS actually does a pretty good job of providing some simple examples of the response headers, such as the key header, Access-Control-Allow-Origin, and other headers that you must use to enable CORS on your web server.

like image 143
Vishal Maru Avatar answered Sep 23 '22 21:09

Vishal Maru