Why Do CORS Issues Occur in Application Project mostly on localhost?

Angular CLI provides a development server that runs on localhost:4200 by default so if you are using a back-end server that runs on a different domain, you may have CORS issues if your server is not configured properly.


Even if your backend is running on localhost such as node.js or PHP, it will listen on a different port such as 9000, which is treated as a different domain for Angular Application.

How to Fix CORS Issues?

Now that we have learned why CORS issues may occur when developing your Angular application. how to fix them?

There are two ways:

Configure the server to send the appropriate CORS headers

Configure Angular CLI proxy: The obvious solution is to configure the backend server properly but that's not possible all the time. For example, you may not have access to the server code due to restriction and all.

Also check out an example of how to configure CORS with TypeScript and Node/Nest.js backend

Most server languages and frameworks provide easy APIs to configure CORS. For example, in PHP, you can simply add the following lines to your PHP file:

header('Access-Control-Allow-Origin: *');

In Node.js and Express server, you can use the cors package (npm install cors --save) as follows:

 // add in server.js file 

const cors = require('cors');

const express = require('express');

const app = express();app.use(cors());

I found this is simple solution to solve the CROS issue on localhost.


Ranveer Meel

Engineering Manager at Chegg Inc.(Remote)

4 年

Neat and clean explained. Keep it up.

要查看或添加评论,请登录

Sushil Kumar的更多文章

  • Inspiring qoute

    Inspiring qoute

    At age 5 his Father died. At age 16 he quit school.

    1 条评论

社区洞察

其他会员也浏览了