免费做字体的网站,c 语言网站建设,wordpress主页广告,wordpress cms门户主题背景#xff1a; 在自己做测试的时候#xff0c;由于需要项目和项目的前端页面使用同样接口访问#xff0c;所以需要将前端代码部署到后端项目下。前端采用vue#xff0c;后端采用springboot。
首先时建立一个vue项目#xff0c;这个可以参照网上的案例#xff0c;创建方…背景 在自己做测试的时候由于需要项目和项目的前端页面使用同样接口访问所以需要将前端代码部署到后端项目下。前端采用vue后端采用springboot。
首先时建立一个vue项目这个可以参照网上的案例创建方式没有区别。创建号之后修改vue.config.js: 主要时修改转发代理的路径target和文件访问路径 publicPath。
const { defineConfig } require(vue/cli-service)
module.exports defineConfig({transpileDependencies: true,publicPath: process.env.NODE_ENV production ? /static : /,devServer: {//以上的ip和端口是我们本机的;下面为需要跨域的proxy: {/: {ws: false,target: http://localhost:9998,changeOrigin: true,pathRewrite: {/^: /}}}}
})代理的target路径改为后端访问地址target: http://localhost:9998其中9998时我们后端springboot项目的端口
publicPath是打包成果物的访问路径,通过dist文件下的index.html就可以知道访问的路径。因为我们的成果物在后端都是放在static下面的。所以需要在打包时将publicPath设置为static。 然后构建npm run build
找到项目下的dist 然后新建一个springboot的web项目
注意需要有以下两个依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId
/dependency 创建好项目之后在resource下创建两个文件static 和 templates
然后将前端打包的结果移动到static和templates下。其中ass、js、favico.ico放到static下方index.html放到templates下 然后添加静态代码的访问路径
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration
public class SpringWebMvcConfig implements WebMvcConfigurer {Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(/static/**).addResourceLocations(classpath:/static/);}
}
首页的访问路径返回index表示访问index.html文件。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;Controller
public class IndexController {GetMapping({/, /index, index.html})public String index(){return index; // 或 return index.html}}
这样就可以通过http://localhost:9998直接访问到后端的页面了。
遇到的问题和修复
1.js文件无法访问到。
原因publicPath没有配置。
如果后端的代码没有配置上下文则publictPath只需要配置为 publicPath: process.env.NODE_ENV production ? /static : /, 如果后端项目配置了上下文则需要将 publicPath再加上上下文例如后端的上下文为/test2则配置为 publicPath: process.env.NODE_ENV production ? /test2/static : /, 这样就可以访问成功了。
2. 想把前端文件单独集成到一个module里面。
可以新建一个module只存放前端文件。只要打包的时候将所有的包打入进去即可。然后再启动服务的模块 引用这个前端文件的module。 3.不想将文件分开放在static和templates文件夹下相统一放在static下 。 static目录是用来保存静态文件的目录, 比如JS, CSS样式, 图片等, 是不需要服务器进行数据绑定的页面此文件下都是静态资源文件最主要的一个特点可以通过浏览器地址栏直接访问而templates文件夹下放置的为动态资源文件夹下的所有页面都需要通过系统来进行调用而不能直接通过网址来访问。 thymeleaf默认会设置并访问templates下的静态资源文件。那么我们可以不使用thymeleaf模板访问thymeleaf目录下的文件吗当然可以springboot默认访问static,resources,public这些文件夹下的文件而没有默认访问templates下的。所以我们需要在application中加上以下配置 spring.resources.static-locationsclasspath:/resources/,classpath:/static/