[英]Correct NodeJS server for Vue.js application
I'm using Vue.js
and the vue-router
and would like to server the static files via Node.JS
. 我正在使用Vue.js
和vue-router
并希望通过Node.JS
服务器静态文件。 So I've create server.js
with the following code: 因此,我使用以下代码创建了server.js
:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
It seems to work, but only when I click around. 它似乎有效,但仅当我单击时才有效。 If I visit ex. 如果我访问前。 my-url.com/some-path/another-path
it fails. my-url.com/some-path/another-path
失败。
Am I missing something? 我想念什么吗?
Ex. 例如 I'm getting: 我越来越:
Cannot GET /cars
with I type www.my-domain.com/cars into the address bar in the browser, but visiting www.my-domain.com and clicking on cars does work. Cannot GET /cars
在浏览器的地址栏中输入www.my-domain.com/cars来Cannot GET /cars
,但访问www.my-domain.com并单击汽车确实可以正常工作。
You need to setup your server to redirect users to the appropriate server location. 您需要设置服务器以将用户重定向到适当的服务器位置。 Please read the Vue Router - HTML5 History Mode docs . 请阅读Vue Router-HTML5历史记录模式文档 。
When using history mode, the URL will look "normal," eg
http://oursite.com/user/id
. 使用历史记录模式时,URL看起来“正常”,例如http://oursite.com/user/id
。 Beautiful! 美丽!Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access
http://oursite.com/user/id
directly in their browser. 但是,这里出现一个问题:由于我们的应用程序是单页客户端应用程序,没有正确的服务器配置,因此如果用户直接在浏览器中访问http://oursite.com/user/id
,则将收到404错误。 Now that's ugly. 现在很丑。Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. 不用担心:要解决此问题,您需要做的就是向服务器添加一条简单的“全部捕获”后备路由。 If the URL doesn't match any static assets, it should serve the same
index.html
page that your app lives in. Beautiful, again! 如果该网址与任何静态资产都不匹配,则该网址应与您的应用程序所在的index.html
页面相同。再次美丽!
The main thing that you need to do is have all routes lead to the root route. 您需要做的主要事情是让所有路由都指向根路由。 Alternatively, since you are using Express, you can leverage the connect-history-api-fallback which the Vue Router docs recommend . 另外,由于使用的是Express,因此可以利用Vue Router文档推荐的connect-history-api-fallback 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.