问题
I am setting up a Play Framework 2.5
server to use Angular
's SPA(single page App) approach and would like to use PathLocationStrategy
that removes the HashTags(#example
)
The page loads fine when I first hit the server, but if I refresh or come back after bookmarking it, gives 404
In the Angular documentation for Angular Router it states that server side configuration is required
There's lots of info on how to do this using nginx
or apache
but how does one do it in Play without a proxy infront?
Here's my angular router configuration:
const routes: Routes = [
{
path: 'main',
component: JobsComponent
},
{
path: 'job-details',
component: JobDetailsComponent
},
{
path: 'job-submit',
component: JobSubmitComponent
},
{
path: '',
redirectTo: '/main',
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/main',
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
Play routes.conf
GET / controllers.Assets.at(path="/public", file="index.html")
回答1:
What's happening is when angular changes the URL bar to /main
, your server is not involved. If you press refresh, the browser will request /main
which it will not find.
Your best approach is to make a route that will catch the desired routes and have it send it back to the index. Here's an example
Make the route to catch the requests:
Can also be a regex as per the Play 2.5 documentation
# Place at the bottom of your routes.conf to be checked last
GET /*anyUrl controllers.CatchAllController.catchAll(anyUrl)
Make the controller
package controllers
import play.api.mvc.{Action, Controller}
import scala.concurrent.ExecutionContext.Implicits.global
class CatchAllController extends Controller{
def catchAll(anyUrl: String) = Action.async { request =>
Assets.at("/public", "index.html").apply(request)
}
}
All links/refreshes should work as intended, no proxy required
来源:https://stackoverflow.com/questions/42495163/angular-html5mode-playframework-gives-404-when-refreshed