Reputation: 6842
When I access method A, I get through, but not method B due to CORS 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:49766' is therefore not allowed access. The response had HTTP status code 404.
Why does one work and the other doesn't? As the error indicates, my client app is running locally also (on port 49766). Its being launched from Visual Studio 2017. The api is running locally within IIS using host headers and an entry in the hosts file.
This is at the top my my asp.net web api controller
[EnableCors(origins: "http://localhost:49766", headers: "*", methods:"*")]
These are my two Angular service methods
//-- this works as expected
getBlogPosts(): Observable<BlogPost[]> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://myapi.testapp.com/api/gfNet/GetBlogPosts",
{ postDate: '', bodyContent: '', Title: '' })
.map((res:Response) => res.json())
.catch(this.handleError);
}
//-- this results in cors error
getBlogPost(postId:string): Observable<BlogPost> {
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let myParams = new URLSearchParams();
myParams.append('Id', postId);
let options = new RequestOptions({ headers: myHeaders, params: myParams });
return this.http.get("http://myapi.testapp.com/api/gfNet/GetBlogPost",options)
.map((res: Response) => res.json())
.catch(this.handleError);
}
Upvotes: 0
Views: 392
Reputation: 221
Cors is not a client side issue, cors is handled by the browser and your server. Your client application is (should be) unaware of it. The browser prefilghts your request of GET /api/gfNet/GetBlogPost with an OPTIONS /api/gfNet/GetBlogPost, and checks if the response's allowed origin is the one you are currently on, and if not, it will not fire your original request.
The status code of 404 indicates that your webserver fails to find the resource your angular application is looking for. This maybe due to using a wrong uri, and instead of your controller, a built in one handles the request. It returns 404 for unknown resource, and not setting the cors headers, because it's not configured to do so.
I suggest inspecting your request in the chrome dev console, make sure they are using the proper url, and see if the response has any meaningful error message, and check the server's log for clues. Testing out your api with a REST client, like postman or a tool like curl might be a good way to make sure your endpoints are working; they don't care about enforcing cors rules, but you can also send OPTIONS request to test your cors policy.
If you fail to identify the issue, you should update question with your implementation of the asp webapi controller.
Upvotes: 1