[英]Can't goto SPA page route when typing route manually in Rails
So far, I made the following setup:到目前为止,我做了以下设置:
app
directory of railsapp
目录中创建 Vue 项目作为目录pubic/spa
directory, ie serve the SPA app in the static filespubic/spa
目录中将构建时的 Vue 项目配置为 output,即在 static 文件中提供 SPA 应用程序spa/about
) Rails throws Routing Errorspa/about
),Rails 会抛出路由错误 I'm figuring that I need a way to tell Rails to always redirect to the SPA app every time the route prefix is spa
我想我需要一种方法来告诉 Rails 每次路由前缀为
spa
时始终重定向到 SPA 应用程序
Is there a way to config rails to do that?有没有办法配置 rails 来做到这一点?
something like this (in route.rb
)像这样的东西(在
route.rb
中)
# every URL prefix is with spa, redirect to static file `spa/index.html`
get "spa#*" => "spa#*"
# or maybe like this?
prefix :spa # there's no `prefix` method option obviously
I figured it out with some digging and testing.我通过一些挖掘和测试弄明白了。 Here's how you config Rails:
以下是配置 Rails 的方法:
class SpaController < ApplicationController
def index
render file: "#{Rails.root}/public/spa/index.html", layout: false
end
end
route.rb
with the new contollerroute.rb
In route.rb
file, add the following line在
route.rb
文件中,添加以下行
get 'spa/*path', :to => 'spa#index'
The wild card *path
is used to catch any "action" while the spa
is served as my prefix as I desired in the beginning.通配符
*path
用于捕捉任何“动作”,而spa
是我一开始所希望的前缀。
So for example:例如:
http://localhost:3000/spa/about
http://localhost:3000/spa/home
All of these routes will be redirect to the same action index
in my SpaController
.所有这些路由都将重定向到我的
SpaController
中的相同操作index
。 In the case of Vue-router, it knows how to handle the routing from there.对于 Vue-router,它知道如何从那里处理路由。
I have not tried the same solution on other SPA frameworks (eg Angular), but I think this solution can work with them as well.我没有在其他 SPA 框架(例如 Angular)上尝试过相同的解决方案,但我认为该解决方案也可以与它们一起使用。
Happy frontend program开心前端程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.