Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Echo和Angular修复刷新错误_Angular_Go_Unexpected Token_Go Echo - Fatal编程技术网

如何使用Echo和Angular修复刷新错误

如何使用Echo和Angular修复刷新错误,angular,go,unexpected-token,go-echo,Angular,Go,Unexpected Token,Go Echo,我正在设置一个web服务器,Go(使用Echo)作为后端,Angular 6作为前端。 我要做的是使用Angular cli“ng new my app”制作一个简单的应用程序,添加一个helloworld组件和“/helloworld”路由,然后使用“ng build--prod”将其构建到生产环境中,后者输出为“dist”文件夹。 文件夹结构: dist ├── assets │ ├── icons │ └── logo.png ├── favicon.ico ├── index.h

我正在设置一个web服务器,Go(使用Echo)作为后端,Angular 6作为前端。 我要做的是使用Angular cli“ng new my app”制作一个简单的应用程序,添加一个helloworld组件和“/helloworld”路由,然后使用“ng build--prod”将其构建到生产环境中,后者输出为“dist”文件夹。 文件夹结构:

dist
├── assets
│   ├── icons
│   └── logo.png
├── favicon.ico
├── index.html
├── main.js
├── polyfills.js
├── runtime.js
└── styles.css
然后我用下面的代码为“dist”文件夹中的静态文件提供服务 梅因,加油

现在,当我使用浏览器并转到“localhost:3000/”时,页面将正确服务,我可以使用href导航,这要感谢角度路由,例如:“localhost:3000/home”,页面将正确显示,但如果我尝试刷新页面,则Echo将返回显示以下内容的页面:

{“消息”:“未找到”}

我知道我可以像这样手动设置路线:

e.File("/home","dist/index.html")
然而,如果我有更多的路线,那么这一切都很麻烦

我需要的是,任何没有为Echo定义的路由都将映射到“index.html”。我尝试过:

e.File("/*", "dist/index.html")

但是我得到了一个有错误的空白页

"Uncaught SyntaxError: Unexpected token <  " 
“未捕获的语法错误:意外标记”
所有3个文件main.js、polyfill.js和runtime.js


我是Echo新手,所以我不知道怎么做。

这个问题与Echo没有严格的关系。Angular执行路由的方式是不从服务器请求页面。它会更改URL,而不会实际从服务器请求另一个页面

因此,当您转到“/home”,然后刷新时,您的浏览器将尝试访问服务器并请求它提供“/home”(与第一次不同,浏览器请求“/”,它映射到“dist/index.html”)。在回送路由中找不到或未定义“/home”。因此,您会收到一条未找到的消息

我建议你做的是做以下关于路由的事情

e.Static("/dist", "dist")
e.File("/*", "dist/index.html")
e.Start(":3000")

在你的
index.html中,在请求的资源的URL之前添加“/dist”。

@Seaskyways answer对我来说非常有用,但在深入研究Echo之后,我也找到了另一个解决方案。Echo有一个处理所有未知路由的NotFoundHandler,所以我所做的只是让它在每次请求未定义路由时返回'index.html'。这是我的密码:

echo.NotFoundHandler = func(c echo.Context) 
    return c.File("dist/index.html")
}
e := echo.New()
e.Static("/", "dist")
e.Start(":3000")

我不确定这是否是一个好方法,但对于像我这样有同样问题的人来说,这是另一个选择。echo中的静态中间件中还有一个
HTML5
选项: e、 g


这似乎可以处理SPA网页。

这迫使Echo在转到
NotFoundHandler
之前查看并检查所有选项。这可能会影响性能。
e.Static("/dist", "dist")
e.File("/*", "dist/index.html")
e.Start(":3000")
echo.NotFoundHandler = func(c echo.Context) 
    return c.File("dist/index.html")
}
e := echo.New()
e.Static("/", "dist")
e.Start(":3000")
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
        Root:   "dist",
        Index: "index.html",
        Browse: true,
        HTML5:  true,
    }))