您的位置:首页 > Web前端 > Vue.js

AspNetCore开源中间件-VueRouterHistory

2022-05-09 22:58 2106 查看

VueRouterHistory

用于Vue单页面应用,使用VueRouter的History模式下,通过AspNetCore提供文件服务。

前言

用过

VueRouter
路由组件的应该都知道,
VueRouter
hash
history
两种模式。
hash
模式会在
url
中插入
#
history
模式下
url
则看上去更加简洁美观。如果想要支持
history
模式则必须要后端服务进行配合。

常用后端服务器配置方式请参考 后端配置例子

后端配置例子

注意:下列示例假设你在根目录服务这个应用。如果想部署到一个子目录,你需要使用 Vue CLI 的 publicPath 选项 (opens new window)和相关的 router base property (opens new window)。你还需要把下列示例中的根目录调整成为子目录 (例如用 RewriteBase /name-of-your-subfolder/ 替换掉 RewriteBase /)。

Apache

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

除了 mod_rewrite,你也可以使用 FallbackResource

nginx

location / {
try_files $uri $uri/ /index.html;
}

原生 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
fs.readFile('index.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.html" file.')
}

res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})

res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})

基于 Node.js 的 Express

对于

Node.js/Express
,请考虑使用
https://www.cnblogs.com/springhgui/p/connect-history-api-fallback
中间件 。

Internet Information Services (IIS)

安装 IIS UrlRewrite

在你的网站根目录中创建一个 web.config 文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

Caddy

rewrite {
regexp .*
to {path} /
}

Firebase 主机

在你的 firebase.json 中加入:

{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

警告

给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后再给出一个 404 页面。

const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})

或者,如果你使用 Node.js 服务器,你可以用服务端路由匹配到来的 URL,并在没有匹配到路由的时候返回 404,以实现回退。更多详情请查阅 Vue 服务端渲染文档 (opens new window)。

原生AspNetCore实现

现如今

AspNetCore
完全不需要依赖
IIS
即可进行部署,如何在
AspNetCore
原生应用中进行支持
VueRouter
history
想必是很多人遇到到的问题之一,也许大部分人选择使用
hash
模式,因为它虽然丑点,但是不需要任何配置即可使用。 为了带给像我一样强烈需要
history
模式的用户,索性写了个中间件,经过测试,能够完美支持
VueRouter
组件
history
模式的部署。

VueRouterHistory

VueRouterHistory
是实现原生
AspNetCore
下支持
VueRouter
history
模式的中间件。

源码已开源在

Github
: https://github.com/SpringHgui/VueRouterHistory

使用方法

  1. 通过
    nuget
    安装
    VueRouterHistory
Install-Package VueRouterHistory -Version 1.0.2
  1. 注册中间件
    app.UseVueRouterHistory()

app.UseRouting()
app.MapControllers()
之后添加
app.UseVueRouterHistory()
;

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

// ==============添加这一行即可================
app.UseVueRouterHistory();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
  1. 将Vue编译后的产物全部放置到
    wwwroot
    文件夹下
  2. 开始体验你的应用吧~

结语

VueRouterHistory
中间件的使用,让我们免于对iis进行配置以实现
history
模式部署,使项目不管是托管在IIS还是直接自托管模式,都不需要进行额外的配置。 欢迎有需要的朋友通过
VueRouterHistory
包进行支持
history
模式,如遇到问题,请提交ISSU。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: