Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 13 CORS on localhost #22992

Closed
pgarzina opened this issue Apr 14, 2022 · 9 comments
Closed

Angular 13 CORS on localhost #22992

pgarzina opened this issue Apr 14, 2022 · 9 comments
Labels
needs: investigation Requires some digging to determine if action is needed needs: repro steps We cannot reproduce the issue with the information given

Comments

@pgarzina
Copy link

Which @angular/* package(s) are the source of the bug?

Don't known / other

Is this a regression?

Yes

Description

After updating Angular 12 to Angular 13 we are no longer able to access our app served on localhost from outside of it, the request is being blocked by CORS.

this is what worked in Angular 12
ng s --project app-search --disable-host-check --port 4207 --deploy-url https://localhost:4207/ --ssl --public-host https://localhost:4207/
and stopped working in Angular 13.

When in development mode we are accessing our https://localhost:4207 app from https://app-staging.cognism.com/

We were looking into the docs around Webpack 4 and Webpack 5 and we can see that the disableHostCheck flag is removed from webpack 5 doc but is in webpack 4 docs. We tried playing around with disable host check and allowed hosts passing it to ng serve per official docs (https://angular.io/cli/serve) but with no luck.

The reason why we need to access localhost is we are using single-spa as a javascript router for front-end microservices. We also tried it on a clean Angular 13 project without any modifications but we get the same behavior.

Not quite sure if this is a bug or do the flags have to be passed in a different way to enable the same behavior that we had before.

Thank you

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

Access to XMLHttpRequest at 'http://localhost:4200/assets/test.csv' from origin 'https://app-dev.cognism.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 13.3.2
Node: 14.15.0
Package Manager: npm 6.14.8
OS: darwin x64

Angular: 13.3.2
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1303.2
@angular-devkit/build-angular   13.3.2
@angular-devkit/core            13.3.2
@angular-devkit/schematics      13.3.2
@schematics/angular             13.3.2
rxjs                            7.5.5
typescript

Anything else?

No response

@alan-agius4 alan-agius4 transferred this issue from angular/angular Apr 14, 2022
@alan-agius4
Copy link
Collaborator

The error seems to indicate that you are trying to access a different host http://localhost:4200 from the one you mentioned initially https://localhost:4207.

Can you please provide the configuration the extract of angular.json for the mentioned application and also the command that you are running including all arguments?

@alan-agius4 alan-agius4 added the needs: more info Reporter must clarify the issue label Apr 14, 2022
@pgarzina
Copy link
Author

Hello, thanks for the prompt answer.
The error I posted in the Please provide the exception or error you saw section is the one I got when retesting this issue with a brand new Angular 13 application.
The one we are getting in our actual dev environment looks pretty much the same
Access to XMLHttpRequest at 'https://localhost:4207/assets/files/industries-classification.json?cache$=true' from origin 'https://app-dev.cognism.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Here is the angular.json and package.json and extra-webpack config that we are using in our app. Just to mention it once again, we did test this on new app, where the angular json and package json are the default ones that the cli provides, without using custom webpack etc, and still got the same issue.

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "cli": {
    "analytics": "5e1e2dd7-84aa-4127-94cf-549190794bdc",
    "defaultCollection": "@angular-eslint/schematics",
    "cache": {
      "enabled": false
    }
  },
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app-search": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "changeDetection": "OnPush",
          "skipTests": true,
          "style": "scss"
        },
        "@schematics/angular:class": {
          "skipTests": true
        },
        "@schematics/angular:directive": {
          "skipTests": true
        },
        "@schematics/angular:guard": {
          "skipTests": true
        },
        "@schematics/angular:module": {},
        "@schematics/angular:pipe": {
          "skipTests": true
        },
        "@schematics/angular:service": {
          "skipTests": true
        },
        "@schematics/angular:resolver": {
          "skipTests": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app-search",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.single-spa.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "preserveSymlinks": true,
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["node_modules/@ng-select/ng-select/themes/ant.design.theme.css", "src/styles.scss"],
            "scripts": [],
            "customWebpackConfig": {
              "path": "extra-webpack.config.js",
              "libraryName": "app-search",
              "libraryTarget": "umd"
            },
            "deployUrl": "https://localhost:4207/"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "app-search:build:production"
            },
            "development": {
              "browserTarget": "app-search:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app-search:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.scss"],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-eslint/builder:lint",
          "options": {
            "lintFilePatterns": ["src/**/*.ts", "src/**/*.html"]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app-search:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app-search:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "app-search"
}


package.json

{
  "name": "app-search",
  "version": "0.517.0",
  "scripts": {
    "ng": "ng",
    "start": "npm run serve:single-spa:app-search",
    "build": "npm run build:single-spa:app-search",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:single-spa:app-search": "cross-env NODE_ENV=production ng build app-search --configuration production --deploy-url /search/",
    "serve:single-spa:app-search": "cross-env NODE_ENV=development ng s --project app-search --disable-host-check --port 4207 --ssl --public-host https://localhost:4207/"
  },
  "private": true,
  "husky": {
    "hooks": {
      "prepare-commit-msg": "jira-prepare-commit-msg"
    }
  },
  "jira-prepare-commit-msg": {
    "messagePattern": "$J $M",
    "jiraTicketPattern": "(\\w+-\\w+-\\d+)"
  },
  "dependencies": {
    "@angular/animations": "~13.2.5",
    "@angular/common": "~13.2.5",
    "@angular/compiler": "~13.2.5",
    "@angular/core": "~13.2.5",
    "@angular/flex-layout": "^13.0.0-beta.38",
    "@angular/forms": "~13.2.5",
    "@angular/localize": "~13.2.5",
    "@angular/platform-browser": "~13.2.5",
    "@angular/platform-browser-dynamic": "~13.2.5",
    "@angular/router": "~13.2.5",
    "@cognism/app-library": "0.0.586",
    "@fortawesome/angular-fontawesome": "^0.10.2",
    "@fortawesome/fontawesome-svg-core": "^6.1.1",
    "@fortawesome/free-brands-svg-icons": "^6.1.1",
    "@fortawesome/pro-duotone-svg-icons": "^6.1.1",
    "@fortawesome/pro-light-svg-icons": "^6.1.1",
    "@fortawesome/pro-regular-svg-icons": "^6.1.1",
    "@fortawesome/pro-solid-svg-icons": "^6.1.1",
    "@ng-bootstrap/ng-bootstrap": "^10.0.0",
    "@ng-select/ng-select": "^8.1.1",
    "@ngneat/cashew": "^1.3.2",
    "@ngneat/until-destroy": "^9.0.0",
    "@ngx-loading-bar/core": "^6.0.2",
    "@types/lodash": "^4.14.179",
    "awesome-phonenumber": "^2.69.0",
    "bootstrap": "^4.6.1",
    "class-transformer": "^0.5.1",
    "install": "^0.13.0",
    "lodash": "^4.17.21",
    "ng-zorro-antd": "^13.1.1",
    "ngx-ellipsis": "^3.1.6",
    "ngx-pagination": "^5.1.1",
    "npm": "^7.24.0",
    "rxjs": "~7.5.4",
    "rxjs-web-observers": "^1.0.2",
    "single-spa": "^5.9.3",
    "single-spa-angular": "^6.0.2",
    "tslib": "^2.3.1",
    "xng-breadcrumb": "^7.2.0",
    "zone.js": "~0.11.5"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^13.1.0",
    "@angular-devkit/build-angular": "~13.2.5",
    "@angular-eslint/builder": "^13.1.0",
    "@angular-eslint/eslint-plugin": "^13.1.0",
    "@angular-eslint/eslint-plugin-template": "^13.1.0",
    "@angular-eslint/schematics": "13.1.0",
    "@angular-eslint/template-parser": "^13.1.0",
    "@angular/cli": "~13.2.5",
    "@angular/compiler-cli": "~13.2.5",
    "@angular/language-service": "^13.2.5",
    "@tailwindcss/aspect-ratio": "^0.4.0",
    "@tailwindcss/forms": "^0.4.0",
    "@tailwindcss/line-clamp": "^0.3.0",
    "@tailwindcss/typography": "^0.5.0",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^14.14.22",
    "@typescript-eslint/eslint-plugin": "5.1.0",
    "@typescript-eslint/parser": "4.28.2",
    "autoprefixer": "^10.4.0",
    "cross-env": "^7.0.3",
    "eslint": "^8.0.0",
    "eslint-plugin-import": "latest",
    "eslint-plugin-jsdoc": "latest",
    "eslint-plugin-prefer-arrow": "latest",
    "husky": "^4.3.7",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~6.0.0",
    "jira-prepare-commit-msg": "^1.5.2",
    "karma": "~6.3.17",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "ngx-tailwind": "^3.0.0",
    "postcss": "^8.4.5",
    "postcss-import": "^14.0.2",
    "postcss-loader": "^6.2.1",
    "postcss-scss": "^4.0.3",
    "protractor": "~7.0.0",
    "styles-loader": "^3.0.0",
    "tailwindcss": "^3.0.23",
    "ts-node": "~10.7.0",
    "typescript": "~4.5.5",
    "webpack-merge": "^5.8.0"
  }
}

webpack config

const singleSpaAngularWebpack = require('single-spa-angular/lib/webpack').default;
const webpackMerge = require('webpack-merge');

module.exports = (angularWebpackConfig, options) => {
  const singleSpaWebpackConfig = singleSpaAngularWebpack(angularWebpackConfig, options);

//https://github.com/single-spa/single-spa-angular/issues/328
  singleSpaWebpackConfig.entry.main = [...new Set(singleSpaWebpackConfig.entry.main)];

  singleSpaWebpackConfig.externals = [/^@cognism\/app-common/];

  const merged = webpackMerge.merge(singleSpaWebpackConfig, {
    module: {
      rules: [
        {
          test: /\.scss$/,
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              ident: 'postcss',
              syntax: 'postcss-scss',
              plugins: [
                require('postcss-import'),
                require('tailwindcss'),
                require('autoprefixer'),
              ],
            },
          },
        },
      ],
    },
  })
  return merged
};

@alan-agius4 alan-agius4 added needs: investigation Requires some digging to determine if action is needed and removed needs: more info Reporter must clarify the issue labels Apr 14, 2022
@pgarzina
Copy link
Author

pgarzina commented May 2, 2022

Is there any additional work we can do to further investigate this issue?
We did reach out to Webpack with an opened issue webpack/webpack#15752 and it seems that instead of disableHostCheck we should set allowedHosts: "all". We have not managed to solve it though :/.

@alan-agius4
Copy link
Collaborator

When using disableHostCheck, Webpack's allowedHosts is set to all.

if (options.disableHostCheck) {
return 'all';
} else if (options.allowedHosts?.length) {
return options.allowedHosts;
}

Providing a reproduction would definitly help us investigate and resolve the issue. A good way to make a minimal repro is to create a new app via ng new repro-app and adding the minimum possible code to show the problem. Then you can push this repository to github and link it here.

This might be related to your directory structure so its really important to get an accurate repro to diagnose this.

@alan-agius4 alan-agius4 added the needs: repro steps We cannot reproduce the issue with the information given label May 2, 2022
@alan-agius4
Copy link
Collaborator

I'm sorry, but we can't reproduce the problem following the instructions you provided.

If the problem persists, please open a new issue following our submission guidelines.

A good way to make a minimal repro is to create a new app via ng new repro-app and add the minimum possible code to show the problem. Then you can push this repository to github and link it here.

@ajaykumarsana
Copy link

@pgarzina
I had the same problem as you do, while migrating angular version to 13 from 12.
Do you find any solution?
Please share.

@pgarzina
Copy link
Author

pgarzina commented Jun 3, 2022

Unfortunately we still have not found the solution.

Its hard to make a minima repro since the issue is related to accessing resources from an outside domain that are served on localhost. So putting it up on stackblitz does not really help. Plus we have to setup single-spa to reproduce the issue, or make a similar setup where another domain is accessing localhost.

As we did zero code changes other than upgrading from angular 12 to angular 13 it seems to indicate that the issue lies somewhere in angular or how they setup/use webpack or whatnot.

We plan to investigate it a bit further as we are now stuck on angular 12 because of this, so if we find anything ill paste it here.

@alan-agius4
Copy link
Collaborator

We did have other similar reports recently and appears that this issue only occurs when using occurs when using the non official @angular-builders/custom-webpack builders.

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Jul 4, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
needs: investigation Requires some digging to determine if action is needed needs: repro steps We cannot reproduce the issue with the information given
Projects
None yet
Development

No branches or pull requests

3 participants