Syntax Error in Angular App: Unexpected token <

后端 未结 30 2084
独厮守ぢ
独厮守ぢ 2020-12-02 20:16

I have an Angular app which runs perfectly in my local and production environment.. After a tiny change I made, I ran the app locally and it works fine.. Then I built the pr

30条回答
  •  执笔经年
    2020-12-02 20:34

    Judging by the number of answers, this issue can show up for a host of reasons.

    I'll add mine incase it helps others. In my case, I was trying to directly hit a url that I wanted to forward back to index.html and let Angular handle it.

    So if I went to http://example.com/some-angular-route/12345

    In the network tab, I noticed that it was serving the scripts with the angular route in the url (http://example.com/some-angular-route/runtime.js)

    Naturally, since nginx couldn't find /some-angular-route/runtime.js, it fell back to serve to index.html since I set try_files (in the nginx config) to test the $uri first and if couldn't find it, serve index.html. So essentially:

    • index.html has a script tag that tries to load http://example.com/some-angular-route/runtime.js
    • fallback in nginx config serves index.html when it can't resolve the file
    • contents of runtime.js are now same as index.html which starts with
    • Since that isn't valid js, you get Uncaught SyntaxError: Unexpected token <

    So how do we get /some-angular-route/ out of the url for runtime.js? We have to make sure you have the base-href set to /. You can do this from the cli with the flag --base-href=/

    That flag will add in your head tag of index.html and will force the browser to resolve all scripts from the root of the site. You can be on a url that includes some-angular-route but load a file like runtime.js (which is a relative url) from /.

提交回复
热议问题