Answer the question
In order to leave comments, you need to log in
How to send rest requests using Angular2?
Good afternoon, I have an application that is on a local server at localhost:3000.
There is a server, also on the localhost with the address localhost:6060/api , I'm trying to send both post and get requests using angular like this:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("Access-Control-Allow-Origin", "*");
headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
headers.append("Access-Control-Allow-Headers", "X-Requested-With,content-type");
this.http.get('http://localhost:6060/api/v1/userinfo', {
headers: headers
})
.subscribe(
data => {
alert(data.json());
},
err => this.alertSome(err.json().message),
() => console.log('Authentication Complete')
);
func GetUserInfo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "X-Requested-With,content-type")
[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (playlist.json, line 0)
[Error] XMLHttpRequest cannot load http://localhost:6060/api/v1/auth. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
Answer the question
In order to leave comments, you need to log in
The point is most likely not in angular, but in the headers that you configure, or in the server settings.
Why do you have it on the client?
headers.append("Access-Control-Allow-Origin", "*");
headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
headers.append("Access-Control-Allow-Headers", "X-Requested-With,content-type");
headers.append('Content-Type', 'application/json');
in GET requests it seems not needed w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
CORS policy headers must be sent by the server.
Those. you have headers
headers.append("Access-Control-Allow-Origin", "*");
headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
headers.append("Access-Control-Allow-Headers", "X-Requested-With,content-type");
should be returned by the server when responding to a request
As a crutch for local development, if CORS is not needed on production, you can run Chrome with the security policy turned off
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question