angryip
angryip

Reputation: 2300

No 'Access-Control-Allow-Origin' header Angular2

I hit a rest service with an Angular2 application.

When doing so, I get a message back stating:

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:3000' is therefore not allowed access.

I have read several posts here, and concluded that inorder to get rid of this issue, I need to specify the header from my server response. Which is exactly what I have done.

If I issue a postman request to the same url, I can see the header returned back:

Access-Control-Allow-Headers →Content-Type
Access-Control-Allow-Method →GET, POST
Access-Control-Allow-Origin →*

Do I need to attach any additional headers to make this work?

Upvotes: 1

Views: 3971

Answers (3)

Luka
Luka

Reputation: 455

REST request sometimes require preflight OPTIONS requests to the selected resource. You can read more about this here:

https://developer.mozilla.org/en-S/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

I have always done this manually, but if you are using RestEasy (which comes with JBoss), since version 3.09 there is a build in helper. Simple usage is explained in this post.

Problems Resteasy 3.09 CorsFilter

If possible I would still advise you not to use CORS, and use a reverse proxy instead.

Upvotes: 2

user5762337
user5762337

Reputation:

There are 2 ways to solve this pretty easy, you can either install an extension in your browser which lets you do cross origin request. Or you create proxy.conf.json file:

{
  "/proxy": {
    "target": "http://route to your rest service",
    "secure": false
  }
}

then you go to your package.json file and change the start configuration:

"scripts": {
    "start": "ng serve --proxy-config proxy.conf.json",

For me this works, check that your REST API is available with the name where I put

"/proxy"

change your service/component which creates the get-requests that the requested url matches your name in proxy.conf.json

Example REST call:

private _restUrl = '/proxy/';    

public testRestConnection = (): Observable <string> => {
let restUrl = this._restUrl + 'path you need';
return this._http.get(restUrl)
  .map((response: Response) => <string>response.text())
  .catch(this.handleError);

}

Upvotes: 0

rkg
rkg

Reputation: 1

@angryip, what browser are you using. It sounds CORS issue. I have this issue in one of my Web API project in .net environment and to resolve this issue I had to install icrosoft.AspNet.WebApi.Cors. I'm not sure what kind development environment you are dealing with. Here is the link I found useful for Enabling CORS : https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Upvotes: -1

Related Questions