Angular App中的语法错误:意外的令牌<

时间:2017-07-20 18:22:13

标签: angular angular-cli

我有一个Angular应用程序,可以在我的本地和生产环境中完美运行。 在我做了一个微小的改变后,我在本地运行了应用程序并且工作正常。然后我构建了项目并将 dist 文件夹复制到Web服务器。问题是,当我尝试访问应用时,我在Chrome检查器中收到以下错误:

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

所以,它似乎是一个错位的角色,但在我的本地环境中,应用程序运行正常我在控制台上没有收到任何警告或错误消息..

31 个答案:

答案 0 :(得分:17)

这很可能是404页面或重定向到提供常规html而不是预期的JavaScript文件的页面的结果。 (HTML页面以<html><!DOCTYPE...>开头) 确保您已正确上传文件并正确访问页面。您可以通过浏览器手动访问URL进行验证,或者查看浏览器开发工具的网络选项卡以检查响应。

答案 1 :(得分:7)

我有同样的问题:

  1. 我运行了命令ng build --aot --prod
  2. 编译没有错误的所有内容
  3. 我删除了服务器上的所有文件,并通过FTP(FileZilla)将其全部复制到Windows Azure服务器
  4. 有时我会收到错误&#34;意外的令牌&lt;&#34;和其他时间不
  5. 昨天我注意到服务器上缺少主[hash] .js,Filezilla没有给我复制它的错误。我然后尝试只复制那个文件。它没有用。当我从文件名中删除哈希部分时,它会毫无问题地复制。

    <强>工作-A-圆

    运行: ng build --aot --prod --output-hashing none

    每次都有效。

    因此,Filezilla或Windows Server不允许具有特定长度的文件名,或者它不喜欢某些哈希值。

答案 2 :(得分:4)

使用angular和express也得到了这个错误。
我想当您构建一个有角度的项目时,该项目不仅存储在“ dist / the-app”中,而且还存储在“ dist / the-app”中,因此这解决了我在快递上的问题。

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

对我来说,此错误是由于未设置所构建应用程序的正确路径所致。

答案 3 :(得分:3)

我是Angular的新手,所以它可能无济于事,或者至少对许多人来说似乎很明显,但是就我而言,它每次我重新加载不是根页面的页面时都发生了,这是由于事实那就是在我的index.html文件中,基本标记看起来像这样<base href="./">,我不得不删除。所以看起来像这样:<base href="/">

答案 4 :(得分:3)

.NET Core解决方案,例如,如果您使用SpaStaticFile服务集合扩展和API项目。

基本href:/

[HttpPost]
[Route("", Name = "creatingThisThing")]
/// etc

答案 5 :(得分:2)

我面临着同样的问题。

就我而言,main.bundle.js丢失了。再次将该文件复制到dist文件夹即可解决此问题。

我要做的另一项更改是更改dist中index.html文件中的以下内容-

<base href=".">

收件人

<base href="/">

答案 6 :(得分:2)

问题出在<base href="/">文件的index.html部分,似乎在dist/{yourProjectName}/内部有angular生成构建文件,但是index.html文件通过了dist/用于生成文件。现在,您有2个选择:

  1. <base href="/">文件的index.html部分更改为<base href="/dist/{yourProjectName}/">,但是现在ng serve命令和ng build之间存在不一致之处,您可以无法通过ng serve查看您的项目。因此,您每次都需要更改该部分!

  2. 我推荐的第二种方法是更改​​项目的输出路径! 转到项目的angular.json文件,并将"outputPath": "dist/{yourProjcetName}",更改为"outputPath": "dist/",不要更改base href

答案 7 :(得分:1)

这取决于您正在使用的服务器。 例如,使用Apache,您可以将.htaccess文件设置为驱动器上的相对路径,应用程序位于RewriteBase。同时设置<base href="">。 对于节点,app.use(express.static(__dirname + '/dist'));应该在app.get之前... 另请注意,构建没有错误,所有文件都被复制到dist。

答案 8 :(得分:1)

节点服务器:server.js

const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
const pathDeploy = path.join(__dirname, 'dist', 'oursurplus');
app.use(express.static(pth));

app.listen(port, () => {
    console.log(`running on port ${port}`);
});

app.get('/*', (req, res) => {
    res.sendFile(path.join(pathDeploy, 'index.html'));
});

package.json必须具有以下脚本:

scripts: {
    "build": "ng build --prod --baseHref=\"./\""
}

答案 9 :(得分:1)

我尝试了以下对我有用的方法。

这里

HTML <base href="xyz"/>指定用于访问资产,例如图像,脚本和样式表等相对URL的基本路径。

例如,在给定<base href="/myApp/">的情况下,如果您的应用想要从URL(例如asset / css / styles.css)访问css文件,它将进入服务器请求myApp / assets / css / styles .css

我已经通过以下两种方式在Xampp服务器上本地部署了我的角度构建:

  1. xampp-> htdocs->“构建文件”(包括资产,.htaccess,index.html等)
  2. xampp-> htdocs-> myApp->“构建文件”(包括资产,.htaccess,index.html等)

对于1。

现在,我希望浏览器访问localhost:80 / assets / css / styles.css,这里我们的资产文件夹位于根目录下,因此要访问css,我们必须放置<base href="./">来访问资产根级别的文件夹。

URL将转到:localhost:80 / assets / css / styles.css

对于2。

我希望我的浏览器访问localhost:80 / myApp / assets / css / styles.css,因此此处的资产文件夹位于根目录下,因此要访问css,我们必须放置<base href="/myApp/">来访问资产myApp内部的文件夹。

URL将转到:localhost:80 / myApp / assets / css / styles.css

答案 10 :(得分:1)

在我的情况下,<!--...-->是导致错误的原因

答案 11 :(得分:1)

在我的情况下,服务器文件中的路由路径不匹配。通往静态路径的路径必须是同时包含index.html和资产目录的目录,而不是资产目录本身。

app.use(express.static(path.resolve(__dirname,'/dist')));

app.get('/*', function (req, res) {
  res.sendFile(path.join(path.resolve(__dirname, '/dist/index.html')));
});

答案 12 :(得分:0)

我通过更改index.html

解决了
<base href="/">

<base href=".">

答案 13 :(得分:0)

我发现此错误是许多可能错误的广泛实例。在使用Jhipster生成项目的应用程序中,我们在index.html中添加了Google Analytics(分析)。我们还尝试了matomo分析。在index.html内部,我们也有脚本标签。

错误是有人在我们的Google Analytics(分析)摘要中注释了一行代码。

以下是错误所在代码的示例:

<script>
        (function (b, o, i, l, e, r) {
            b.GoogleAnalyticsObject = l;
            b[l] || (b[l] =
                function () {
                    (b[l].q = b[l].q || []).push(arguments)
                });
            b[l].l = +new Date;
            e = o.createElement(i);
            r = o.getElementsByTagName(i)[0];
            e.src = '//www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e, r)
        }(window, document, 'script', 'ga'));
        ga('create', '123123'); <! --
        ga('send', 'pageview');
        -->

    </script>

请注意最后三行中有<! --的位置。那会给我们带来错误。

在index.html脚本标记中,要注释掉一行,我们使用\\双反斜杠。可能有人尝试使用<!-- -->将此行注释掉。

这很棘手,因为它可能在任何地方。
但从index.html

开始总是一个好地方

希望这会有所帮助。

答案 14 :(得分:0)

从答案的数量来看,这个问题可能有很多原因。

我会添加我的,以帮助他人。就我而言,我试图直接打一个我想转发回index.html的URL,然后由Angular处理。

所以如果我去http://example.com/some-angular-route/12345

在“网络”标签中,我注意到它正在使用网址(http://example.com/some-angular-route/runtime.js)中的角路由来提供脚本

自然地,由于nginx找不到/some-angular-route/runtime.js,因此由于我设置了try_files(在nginx配置中)首先测试$ uri,如果不能,它便退回到了index.html。找不到它,请提供index.html。所以本质上:

  • index.html具有尝试加载http://example.com/some-angular-route/runtime.js
  • 的脚本标签
  • nginx配置中的后备无法解析文件时会提供index.html
  • runtime.js的内容现在与以<html>开头的index.html相同。
  • 由于这不是有效的js,您将获得Uncaught SyntaxError: Unexpected token <

那么我们如何从/some-angular-route/的网址中获取runtime.js?我们必须确保将base-href设置为/。您可以从cli中使用标志--base-href=/

该标志将添加到您的index.html头标记中,并将强制浏览器从站点根目录解析所有脚本。您可以使用包含some-angular-route的URL,但要从/加载类似runtime.js的文件(相对URL)。

答案 15 :(得分:0)

在ng构建之后,转到dist /您的项目文件夹,说“某事”。然后打开index.html文件并更改默认的基本URL。

如果将项目文件夹放在nginx或apache上,则游览基础URL应该为

<base href="http://localhost/something/">

在我的情况下,Angular的版本为:7.1.4

答案 16 :(得分:0)

我之所以遇到此问题,是因为我已经生成了组件,但是布线不正确或没有进行布线,所以我认为你们当中的任何一个首先都会遇到此错误,请检查是否有不完整的东西。

对我来说是因为路由。

答案 17 :(得分:0)

对我来说有2个问题,

  1. / dist文件夹被源代码管理忽略,因此我必须应用以下命令来添加它。

    git add /dist/* -f

  2. dist / index.html文件具有以下路径:

<base href="/project-name/" />

我将其更改为: <base href="/" />

效果很好。

答案 18 :(得分:0)

<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">

将以上几行添加到index.html

原因:Chrome浏览器会缓存index.html,因此main.hash.js中的哈希不会得到更新,因此我们会收到“意外的令牌错误<”。

答案 19 :(得分:0)

我遇到了同样的问题,并意识到我在上次部署后更改了app.use(express.static(静态文件夹))语句,导致同样的unexpected token <错误。

确保您的app.use(express.static(static folder))语句包含相应的静态文件夹,其中包含js和css文件所在的位置以及相对于运行节点的位置。

如果您正在使用Angular并进行预编译(ng build --prod),则将您的前端Angular代码放入包含这些文件的dist文件夹中,而不将后端节点文件放在同一文件夹中(例如,单独的后端),那么您可能还需要包括正确的路径。

以我的示例为例,我在项目目录中的/ dist中有预编译的(ng build --prod)Angular文件。请注意,在预编译之前,我还将angular.json更改为"outputPath": "dist",以确保这是预编译的Angular代码可以使用的地方。我刚刚启动节点服务器的server.js文件位于项目根目录,但是包含app.use(express.static(static folder))语句和所有其他后端节点代码的app.js文件位于名为/ backend的文件夹中。在这种情况下,以下语句均对我有用,可以正确找到js和css文件并消除unexpected token <错误:

  app.use(express.static(path.join('dist')));

  app.use(express.static(path.join(__dirname, '../dist')));

这两个语句都适当地指示节点在/dist文件夹中查找静态js和css文件。

答案 20 :(得分:0)

您可以尝试将index.html文件中的基本标记从<base href="/">更改为<base href="/project-app/">

答案 21 :(得分:0)

尽管要进行快速解决(绝对不建议这样做,也不是一种好的做法),您可以采用非生产模式进行构建。仅尝试ng build

答案 22 :(得分:0)

在我的情况下,这是由于UTF-8字符输入错误造成的。

语法为:

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

首先,只需将å替换为a即可解决。但是,那并不是真正的解决方案。

解决的办法是在文本周围添加''

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

错误:

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>]

答案 23 :(得分:0)

.htaccess文件中进行了一些更改,我设法解决了这个问题。

我将某些行从http://jsfiddle.net/8dvhew3q/4/更改为以下内容:

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

答案 24 :(得分:0)

我遇到了同样的问题,很烦人。我尝试了这里找到的几种解决方案,但没有一个可行。

在Azure门户中应用程序的“应用程序设置”刀片中添加以下内容即可达到目的-

应用设置名称:WEBSITE_NODE_DEFAULT_VERSION 值:6.9.1

> 之前和之后-摘录自部署日志。

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

screen capture from azure portal

答案 25 :(得分:0)

根据我的经验,我将其他资产添加到wwwroot是冲突的,以检测asp.net核心的静态基地址。

例如:

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

angular -> src -> assets发生冲突 并显示此错误

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

答案 26 :(得分:0)

我有一个webapi项目和角度,在尝试不同的方式后,我解决了重定向问题

    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();
    }

答案 27 :(得分:0)

只需添加/项目的文件夹名称,就像添加Gerardo Tarragona一样。

示例:

/myProject

此致

答案 28 :(得分:-1)

我也有几次相同的问题,我用这种方式解决了:

使用root以外的用户(ubuntu-normaluser)构建项目

root$ chown -R ubuntu:ubuntu my-project-folder/
ubuntu$ cd my-project-folder/
ubuntu$ npm install 
ubuntu$ ng build -xxx params xx etc

在生产服务器中显示nginx用户:

root$ grep -rh user /etc/nginx/*
user www-data; # in my case

现在移动或替换my-project-folder

root$ mv my-project-folder/ /var/www/awesome.com

并更改对nginx用户的权限

root$ chown -R www-data:www-data /var/www/awesome.com

(Y)

答案 29 :(得分:-1)

在您的index.ts更改中

<!--doctype html-->
<!DOCTYPE html>

记住... <!DOCTYPE>声明不区分大小写。 检查以下link

答案 30 :(得分:-3)

就我而言,我只需要对页面进行“硬刷新”以清除其缓存(在Linux下使用Chrome,可通过按 ctrl + F5 )。之后,一切又恢复正常了。

干杯