Angular deployment without server - Error: Securit

2019-02-21 04:36发布

I have a simple web application in Angular v5. This is a purely client-side application in the meaning of it doesn't use any server-side (this is a basic calculator application that load data from JSON file with some measurements and display to the user some analysis according to that JSON).

During development I've tested the application using the Angular-cli "serve", by running - ng serve command, and it works great.

Now I wont to bundle my app and start using it. I would like to run this app locally on my machine without any server.
According to the Angular documentation, to bundle the application to deployment, I should run the command: ng build --prod --base-href=./. There to flag --prod will deploy a minified and uglified version of the application. And the --base-href=./ will set <base href="./"> in the index.html to allow me loading the application files (all the ABC.bundles.js file) directly from the local machine.

Now, when I'm opening the dist/index.html file I can see that all the scripts have loaded, however, I have an error in the console:

ERROR Error: Uncaught (in promise): SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'file:///C:/.../dist/' cannot be created in a document with origin 'null' and URL 'file:///C:/.../dist/index.html'.

How do I deploy/bundle my application to run locally, without a server?

3条回答
ゆ 、 Hurt°
2楼-- · 2019-02-21 05:29

When using angular-router you need a server-side since the router is used to serve pages.

To solve these issue you have 2 choices:

  1. Use some sort of light-weight server like NPM's http-server which allow you to run a server on a local machine from the command-line.

  2. Drop the angular-router completely - Yes this is a bit extreme solution and I'm sure it will not be a valid solution to anybody with more than 2 pages in his application. But if you have a very very simple app with one page only and you don't need routing capabilities then this is a valid solution.

查看更多
Ridiculous、
3楼-- · 2019-02-21 05:31

Try using HashLocationStrategy

https://angular.io/api/common/HashLocationStrategy https://angular.io/guide/router#hashlocationstrategy

In your module

imports [
RouterModule.forRoot(routes, {useHash: true})
]
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-21 05:37

In your routes configuration add;

RouterModule.forRoot(routes, {useHash: true});

In your index.html do this;

<!-- <base href="/"> --> <script>document.write('<base href="' + document.location + '" />');</script>

And then build with --base-href ./ e.g

ng build --prod --base-href ./

source https://github.com/angular/angular/issues/13948

查看更多
登录 后发表回答