D
D
Dmitry Medinsky2021-03-01 14:51:58
Angular
Dmitry Medinsky, 2021-03-01 14:51:58

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))


I get the error:
Access to XMLHttpRequest at ' localhost:3000 ' from origin ' localhost:4200 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Even if I add the title:
this.http.get('http://localhost:3000', {
      headers: {
        'Access-Control-Allow-Origin': '*'
      }
    })
      .subscribe(res => console.log(res))


Or this way:
this.http.get('http://localhost:3000', {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*'
      })
    })
      .subscribe(res => console.log(res))


Error:
Access to XMLHttpRequest at ' localhost:3000 ' from origin ' localhost:4200 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I just can’t understand where it can come from and how to solve it, because everything worked in other projects.

Please help me with this heresy.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2021-03-01
@Dimski

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-...

M
Mikka, 2022-03-24
@Horny_515

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 question

Ask a Question

731 491 924 answers to any question