Answer the question
In order to leave comments, you need to log in
CORS blocks all Angular requests. How to fix?
Good day!
I ran into a very strange problem, the browser began to block them all for trite simple requests.
Sending a request:
this.http.get('http://localhost:3000')
.subscribe(res => console.log(res))
this.http.get('http://localhost:3000', {
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.subscribe(res => console.log(res))
this.http.get('http://localhost:3000', {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*'
})
})
.subscribe(res => console.log(res))
Answer the question
In order to leave comments, you need to log in
You send a request from localhost:4200 to localhost:3000 in order to manage such requests, the server must support CORS, obviously it does not.
It is very bad not to know the
hardware https
://developer.mozilla.org/en-US/docs/Web/Secur... -a... https://github.com/angular/angular-cli/pull/1896 https://itnext.io/angular-cli-proxy-configuration-...
You do not support cors on the server side. Judging by port 3000, I can assume that you are using Express (nodeJS) + Angular
If I'm right, then you need to add import
const cors = require('cors')
Then install cors - npm install
Then add
res.statusCode = 200 to the API requests themselves ;
res.setHeader('Content-Type', "application/json"); //In my case I get json
res.setHeader('Access-Control-Allow-Origin', "*"); //Either a specific host (an array group is supported)
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); //Required request types
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
At the end, before specifying the port, add the use of cors to
exit app.use(cors())
app.listen(3000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question