[Fixed] Hosting angular and nodejs on the same domain (cpanel)


I have my angular application running on subdomain.maindomain.com
My api is running on api.maindomain.com

My nodejs and angular are both hosted on the same subdomain.

I have a proxy.conf.json file that looks like this:

    "/api": {
        "target": "api.maindomain.com/api/",
        "secure": false

My start script is:

 "start": "ng serve --proxy-config proxy.conf.json -o",

Whenever I build and deploy my app, I can access: api.maindomain.com/api/users through the browser or Postman and it works 100%. It gives me the desired API response.

When I try to make the API call on angular on subdomain.maindomain.com however, the api call goes to
when it should be calling

How do I fix this?


Your proxy setting is only for the development purposes. It was implmented to make it easier for the developers to deal with the Backends that are hosted in anohter domain (different host or completly another domain). For this, it won’t be shipped with the production deployment.

The api.maindomain.com is actually other host and different than the subdomain.maindomain.com, so the request will fail.

The origin header is responsable for this. It is added by the browser for every request automatically and equals the same domain you are accessing.

When trying to access the API by the Browser it will always work. When accessing the API directly, the Browser will add the origin header with the same domain (As you are accessing it from the same domain), so there will no issues with it. For Postman, there is no origin header when sending so it won’t fail too.

To fix this, you either need to host both of them on the same host, or you will have to enable CORS for your subdomain. If you are using Express, you can use the CORS middleware similar to this:

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})

You can find more info about the CORS here: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

Leave a Reply

(*) Required, Your email will not be published