12

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

9
  • 4
    CORS should be enabled by the server from which you are requesting the resource, not from Angular. Commented May 30, 2018 at 14:47
  • @DavidAnthonyAcosta, Angular2+ is client library and it's not used for server side rendering. I use only, I suppose webpack-dev-server should be configurated Commented May 30, 2018 at 14:55
  • No, webpack does not need to be configured for CORS. Angular i snot a client library, it is a Framework. See Ab Ebube's answer below. As you can see, he is configuring cors server side NOT client side Commented May 30, 2018 at 14:58
  • @DavidAnthonyAcosta, I use node js also, didn't think that node js should be configurated Commented May 30, 2018 at 15:02
  • Any server you use needs to be configured. If you are using NodeJS server, then you can use the npm package called CORS which lets you configure it pretty easily Commented May 30, 2018 at 15:02

4 Answers 4

18

**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.

Sign up to request clarification or add additional context in comments.

6 Comments

I don't use ExpressJs
You have to enable CORS on the API Server (Where API Developed). On which server API developed?
I got API from unknow server for me. I just need to use it
I can get/see data from direct link API, but not via Angular
You have to tell API developer to enable CORS. Happy coding
|
2

If you are using .NET Api then add this to your WebApiConfig.cs file

    public static void Register(HttpConfiguration config)
    {
        var enableCorsAttribute = new EnableCorsAttribute("*",
                                           "Origin, Content-Type, Accept",
                                           "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

1 Comment

you have to install nuget packet Microsoft.AspNet.WebApi.Cors for this
2

You mentioned webpack-dev-server, which of course can handle CORS since it's using express behind the scenes. In your webpack config

devServer: {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
  }
},

Comments

1
Access-Control-Allow-Origin

Is response header not request header. You must add this header to your resfull (server)

1 Comment

This took me like two months to understand that it is not a certain browser's feature to block the cors request but the server's configuration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.