3

spring | vue 和 spring boot 整合部署

 1 year ago
source link: https://benpaodewoniu.github.io/2023/03/10/spring49/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vue 和 spring boot 整合部署

姑苏城外一茅屋,万树梅花月满天

虽然是单体部署,但是也是前后端分离项目,前后端的沟通还是通过 restful,只不过,前后端都打在了一个 jar 包中。

网上大部分教程写的都很粗浅,这里说一下整个过程。

如果,你的前端项目可以 npm run server 的话

你只需要 npm run build,将 dist 文件夹里面的内容 copyresources/static 里面即可。

如果你的配置为

server.port=8002

那么,你只需要访问 127.0.0.1:8001 即可。

这里需要注意的是,前端和后端都共享一个端口。

比如,你的网页页面时 127.0.0.1:8002,但是,restful 请求是 127.0.0.1:8002/login

如果,你的项目中有拦截器,比如

registry.addInterceptor(authInterceptorService)
.addPathPatterns("/**");

这是说明你的所有路径都必须通过 authInterceptorService 拦截器的校验规则。

如果这个时候你访问 127.0.0.1:8001 可能校验不通过,导致返回不了正确界面。

所以你的拦截器,不能拦截所有的页面,具体细节请参考

在前后端分离,当前端和后端使用端口不一致的时候,就会出现这种情况。

可以在启动类中添加下面的跨域代码。

package com.yamlgameswap.back;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootApplication
public class BackApplication {
public static void main(String[] args) {
SpringApplication.run(BackApplication.class, args);
}

@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);

UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}

@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK