Syntax Error in Angular App: Unexpected token <

2019-01-17 16:04发布

问题:

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 project and copied the dist folder to the web server. The problem is when I try to access to the app I get the following error in the Chrome Inspector:

Uncaught SyntaxError: Unexpected token < inline.1a152b6….bundle.js:1
Uncaught SyntaxError: Unexpected token < polyfills.1553fdd….bundle.js:1
Uncaught SyntaxError: Unexpected token < vendor.94d0113….bundle.js:1
Uncaught SyntaxError: Unexpected token < main.d6f56a1….bundle.js:1

So, it seems like it is a misplaced character but in my local environment the app works fine I don't get any warning or error message on the console..

回答1:

This is most likely the result of a 404 page or a redirect to a page that serves regular html instead of the expected JavaScript files. (A HTML page starts with <html> or a <!DOCTYPE...>) Make sure that you have correctly uploaded the files and access the page correctly. You can verify by manually accessing the URL with the browser or look into the network tab of your browser development tools to inspect the response.



回答2:

I had the same issue:

  1. I ran the command ng build --aot --prod
  2. Everything compiled without an error
  3. I deleted all the files on the server and copied it all across via FTP(FileZilla) to a windows Azure server
  4. Sometimes I get the error "Unexpected token <" and other-times not

Yesterday I noticed that the main[hash].js was missing on the server and that Filezilla did not give me an error copying it.I then tried copying only that file.It did not work. When I removed the hash part from the filename it copies without a problem.

Work-a-round

Run: ng build --aot --prod --output-hashing none

Which works every-time.

So either Filezilla or Windows Server does not allow filenames with a specific length or it does not like certain hashes.



回答3:

I'm totally new to Angular so it may not help or at least seem obvious to a lot of you, but in my case it happened every time I reloaded a page that's not the root page, and it came from the fact that, in my index.html file, the base tag looked like this <base href="./">, I had to remove the . so it looks like this : <base href="/"> .



回答4:

got this error as well using angular with express.
I guess when you build an angular project the project is stored in 'dist/the-app' not just 'dist' so this solved my problem on express.

   // Point static path to dist
   app.use(express.static(path.join(__dirname, 'dist/the-app')));

for me, this error was due to not setting the proper path of the built application.



回答5:

It depends on the server, you are using. For example with Apache, you set the .htaccess file to a relative path on your drive, where your app is located with RewriteBase. Also set the <base href=""> accordingly. With node, the app.use(express.static(__dirname + '/dist')); should go before app.get... Check also, that the build had no errors and all files were copied to dist.



回答6:

Just add after of / the folder name of you project just like said Gerardo Tarragona.

Example:

/myProject

Regards



回答7:

I have a webapi project and angular, after trying different ways, following resolved the redirection issue for me

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        //For angular url rewriting
        app.Use(async (context, next) =>
        {
            await next();
            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        })
        .UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List<string> { "index.html" } })
        .UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc();
    }


回答8:

In my experience i'm add other assets to wwwroot is conflicted to detect static base address for asp.net core.

For example:

wwwroot
      |--> assets 
                  |---> ckeditor

Is conflict with angular -> src -> assets and show this error

Uncaught SyntaxError: Unexpected token < inline.1a152b6….bundle.js:1
...


回答9:

In my case the <!--...--> was the cause of the error



回答10:

I had the same issue, very irritating. I tried several of the solutions found here, but none worked.

Adding the following in the Application Settings blade of the application in the Azure portal did the trick -

App Setting Name: WEBSITE_NODE_DEFAULT_VERSION Value: 6.9.1

> Before and after - excerpts from the deployment log.

remote: The package.json file does not specify node.js engine version constraints.
remote: The node.js application will run with the default node.js version 0.10.40.
remote: Selected npm version 1.4.28


remote: The package.json file does not specify node.js engine version constraints.
remote: The node.js application will run with the default node.js version 6.9.1.
remote: Selected npm version 3.10.8



回答11:

With a little change in the .htaccess file i managed to fixed this problem.

I changed some lines from https://angular.io/guide/deployment#fallback to the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html


回答12:

In my case it was the result of incorrect input of UTF-8 characters.

Syntax was:

<component [inputField]="Artikelns Mått"></component>

First it was solved by just replacing the å with a. But, thats not really a solution.

What solved it was adding '' around the text.

<component [inputField]="'Artikelns Mått'"></component>

Error:

Error: Template parse errors:
Parser Error: Unexpected token 'å' at column 11 in [Artikelns mått] in CadComponent@25:28 ("
    <div class="col-md-4">
        <lte-box>
            <lte-box-header [ERROR ->][headerTitle]="Artikelns mått"></lte-box-header>
            <lte-box-body>
                <table "): CadComponent@25:28
Parser Error: Lexer Error: Unexpected character [å] at column 12 in expression [Artikelns mått] at column 13 in [Artikelns mått] in CadComponent@25:28 ("
    <div class="col-md-4">
        <lte-box>
            <lte-box-header [ERROR ->][headerTitle]="Artikelns mått"></lte-box-header>
            <lte-box-body>
                <table "): CadComponent@25:28
    at SyntaxError.BaseError [as constructor] (webpack:///./@angular/compiler/src/facade/errors.js?:31:27) [<root>]
    at new SyntaxError (webpack:///./@angular/compiler/src/util.js?:163:16) [<root>]
    at TemplateParser.parse (webpack:///./@angular/compiler/src/template_parser/template_parser.js?:170:19) [<root>]
    at JitCompiler._compileTemplate (webpack:///./@angular/compiler/src/jit/compiler.js?:381:68) [<root>]
    at eval (webpack:///./@angular/compiler/src/jit/compiler.js?:264:62) [<root>]
    at Set.forEach (<anonymous>) [<root>]
    at JitCompiler._compileComponents (webpack:///./@angular/compiler/src/jit/compiler.js?:264:19) [<root>]
    at createResult (webpack:///./@angular/compiler/src/jit/compiler.js?:146:19) [<root>]
    at Zone.run (webpack:///./zone.js/dist/zone.js?:112:43) [<root> => <root>]
    at eval (webpack:///./zone.js/dist/zone.js?:534:57) [<root>]
    at Zone.runTask (webpack:///./zone.js/dist/zone.js?:150:47) [<root> => <root>]
    at drainMicroTaskQueue (webpack:///./zone.js/dist/zone.js?:432:35) [<root>]