假设我有一个vuejs webapp:www.example.com。它使用 vue-router,所以有一堆预定义的路由:example.com/signin、/signup、/dashboard(当用户登录时(,还有一个 * 路由,如果找不到路由,它会重定向到/404:
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/signup',
name: 'signup',
component: () => import('@/views/SignIn.vue')
},
{
path: '/signin',
name: 'signin',
component: () => import('@/views/SignIn.vue')
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('@/views/Dashboard.vue'),
beforeEnter: requireAuth
},
{
path: '/404',
name: '404',
component: () => import('@/views/NotFound.vue')
},
{
path: '*',
redirect: '/404'
}
]
})
同一网站(www.example.com(也将提供一个API(即 www.example.com/api/some-end-point(。有没有办法在 vue-router 中配置将用户送出应用程序而不是重定向到/404?
这取决于您是处于开发模式还是处于生产版本。在开发模式下,您可以添加或创建vue.config.js
添加配置devServer
。您可以代理到api
devServer
。假设您在端口上运行 NodeJS 或 PHP 应用程序3000
您可以将以下内容添加到vue.config.js
中。在此设置中,npm run serve
http://localhost:8080/api
将路由到您的 api。
module.exports = {
devServer: {
host: '0.0.0.0',
port: 8080,
https: false,
hotOnly: true,
proxy: {
'/api': {
target: 'http://localhost:3000'
}
}
},
}
如果您处于生产模式,则可能需要像NGINX
这样的网络服务器来apache
。例如,在 Nginx 中,您需要通过代理将/api
位置与 api 分开,其余位置与 vue 文件分开。下面是一个示例
...
location /api {
proxy_pass http://myapi:3000;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
expires off;
access_log off;
if_modified_since off;
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
proxy_no_cache 1;
}
location / {
try_files /path/to/my/vue/build/files /;
}
...