0

I am new to Angular2. I have created a service in my local machine in WCF and runs it. A simple method is created that returns a string, codes is shown below.

    public string JSONData(string id)
    {
        return "You requested product is " + id;
    }     

Now I want to access that service in my Angular2 app in my service.ts file. Code in accessing the service method is shown below:

   testService(){
        return this._http.get('http://localhost:49753/RestServiceImpl.svc/json/4')
        .map(res => res.json())
        .do(data => console.log("Testing service" + JSON.stringify(data)))
        .catch(this.handleError);
    }

But when I run the codes, I got the error below: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http...."

Is there a way to call my WCF service without hosting my service in other machine?

wal
  • 793
  • 4
  • 14
  • 19

1 Answers1

-1

You are getting this problem as header which you are sending is not matched with the headers in backend

So let suppose In frontend you sending headers

contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.

So in backend 'Access-Control-Allow-Headers' should have all above headers see below

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

CDspace
  • 2,639
  • 18
  • 30
  • 36