How can I use angular 2 request data
When we send data, including JSON content, to an external api, an error occurs Access-Control-Allow-Origin
. The solution to this problem is to use x-www-form-urlencoded content
. Is there anyway to use JSON?
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=info@mail.com&password=123", this.options )
.map(res => res.json())
.map(user => {
if (user) {
console.log(user);
}
return !!user ;
});
}
Another solution:
1. Install the extension Access-Control-Allow-Origin in Chrome
2.lunch web api in localhost bu looking for another way
3.enable CORS on IIS7
but the problem is not solved!
+3
source to share