Allahyar
Allahyar

Reputation: 209

How can i use angular 2 request data

When we send data including JSON content to an external api, an Access-Control-Allow-Origin error occures. The solution of this problem is that using x-www-form-urlencoded content. Is there anyway to use JSON instead ?

JSON content :

    this.http.post('/api/login', {
      email: email,
      password: pass
    }).map(res => res.json())
      .subscribe(response => {
        console.log(response);
      } , error => console.error(error));
  }

x-www-form-urlencod:

  this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.options = new RequestOptions({ headers: this.headers, method: 'post'});
    return this.http.post('/api/login', "[email protected]&password=123", this.options )
        .map(res => res.json())
        .map(user => {
            if (user) {
                console.log(user);
            }
            return !!user ;
        });
}

Other solution :

1.install Access-Control-Allow-Origin extension in Chrome
2.lunch web api in localhost bu looking for another way
3.enable CORS on IIS7

but problem is not resolved !

Upvotes: 3

Views: 151

Answers (1)

Mohammad Ghalgar
Mohammad Ghalgar

Reputation: 66

WebConfig :

 <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol>​

WebApiConfig :

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET,POST,PUT,DELETE");
config.EnableCors(cors);

Upvotes: 1

Related Questions