vaibhav Srivastava
vaibhav Srivastava

Reputation: 11

Angular2, REST Service POST Call error : "Cross-Origin Request Blocked"

I am trying to call REST APIs from development environment(localhost:4200) using Angular 2 (version 4.0.0)

getting the below error message: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/auth. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

Here I am providing a code sample for reference:

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

return this.http.post(this.loginUrl, 'POST_Parameters', {
       headers: headers
}).map(res => {
       console.log(res);
});

Can someone please help me to find out solution for this issue?

Upvotes: 1

Views: 5297

Answers (4)

Sourav Golui
Sourav Golui

Reputation: 633

You are in local server. You need to run api and angular app on same server. When you upload project on same production server I hope This error will not shown.

Upvotes: 0

thangavel .R
thangavel .R

Reputation: 466

As per Browser policy CORS is not allowed. If you are using POSTMAN then this error won't not occur.

CORS error should only remove by server side. Hence you should set header in your backend code.

If you are using express as your backend ...

app.use(function(req,res){
    res.header('Access-Control-Allow-Origin', '*');});

Upvotes: 0

ircmgr
ircmgr

Reputation: 77

on a project of mine i just went to my server (apache2 on linux 16.04 ) and i just added the "Header set Access-Control-Allow-Origin "*"" on the virtual server config file

Upvotes: 1

A. Tim
A. Tim

Reputation: 3206

CORS must be enabled by backend. Depending on backend framework, usually you must send specific header that backend can recognize. But until you explicitly enable CORS support on backend, sending header is useless

Upvotes: 1

Related Questions