如何在前端和后端位于同一服务器上时处理路由

时间:2017-05-24 16:32:03

标签: reactjs spring-mvc spring-boot

我有一个Spring启动,它上面运行了一些服务。它还有一个具有自己路由的反应视图。这是否可能,我可以在同一台服务器中拥有后端路由和前端路由吗?

由于

3 个答案:

答案 0 :(得分:1)

经过一些研究,前端路由是一个误导性的术语,尽管它被广泛使用。路由需要始终转到后端,后端决定请求会发生什么。如果React.js,Angular或任何其他前端框架正在处理路由,则后端需要 转发 所有来自前端的请求到前端再次,这是具有JS和CSS的HTML页面。为了实现Spring框架,我使用 tuckey 过滤器将请求转发到html页面。神奇的词是 FORWARDING 对html页面的请求。

tuckey过滤器的urlrewrite.xml再次将请求转发给ui,它看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<!-- Configuration file for UrlRewriteFilter http://www.tuckey.org/urlrewrite/ -->
<urlrewrite>
 <rule match-type="regex">
    <name>Front-end forwarding</name>
    <note>Forwarding all routes from the front-end to the ui controller</note>
    <condition type="request-uri" operator="notequal">^\/([\-\w\.]+)([\-/\w\.]*)(\.([\-\w]+))$</condition>
    <from>^\/ui\/([/\-\w]+)$</from>
    <to type="forward" last="true">/ui</to> <!--This is where the ui controller is located-->
 </rule>
</urlrewrite>

这是tuckey过滤器java配置:

@Component
public class TuckeyFilterConfigurations extends UrlRewriteFilter{

private static final String CONFIG_LOCATION = "classpath:/urlrewrite.xml";

@Value(CONFIG_LOCATION)
private Resource resource;

@Override
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
    try {
        Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "");
    checkConf(conf);
    } catch (IOException ex) {
        throw new ServletException("Unable to load URL-rewrite configuration file from " + CONFIG_LOCATION, ex);
    }
 }
}

最后,为html页面提供服务的控制器看起来像:

@Controller
public class UiController {

  @RequestMapping("/ui")
  public String entrance(){
      return "index.html";
  }
}

答案 1 :(得分:0)

你可以拥有,但将路由逻辑放在一个地方总是一个好习惯,因为一旦它的大小增加,它对应用程序的故障排除有很大帮助。

这怎么会有效,你举个例子吗?当我有一个前端路由到某个链接时,它总是指向后端。我知道有#routing,但我正在寻找常规“/”路由的解决方案?

您可以使用BrowserRouterStaticRouter来实现它。以下是React培训团队使用StaticRouter - Server Rendering with React实现服务器渲染的精彩指南。

答案 2 :(得分:0)

第1步在pom.xml中添加以下内容:

        <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <optional>true</optional>
        </dependency>

第2步,请在您的application.properties中添加以下两行:

#reload static content lively without reboot spring boot app
spring.devtools.livereload.enabled: true

#specify the static file location
spring.resources.static-locations: file:${your-frontend-file-root-location}