Net Core API +Vue Nginx集成发布

1、在net core api  Startup.cs 中的Configure中设置默api默认页面 关键代码 app.UseFileServer

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
#if DEBUG
            app.UseStaticFiles(); //开启访问静态文件/wwwroot目录文件,要放在UseRouting前面
#else
            app.UseStaticFiles(new StaticFileOptions()
            {
                ServeUnknownFileTypes = true,
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
                Path.Combine(Path.GetDirectoryName(typeof(Startup).Assembly.Location), "wwwroot")),//wwwroot相当于真实目录
            });

            app.UseFileServer(
            new FileServerOptions()
            {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider( Path.Combine(Path.GetDirectoryName(typeof(Startup).Assembly.Location), "wwwroot")),
                EnableDirectoryBrowsing = true,
                DefaultFilesOptions ={
                    DefaultFileNames = new List<string>(){ "/index.html" }
                },
                EnableDefaultFiles = true
            });  
#endif
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

详细使用即讲解,参见官方文档:ASP.NET Core 中的静态文件 | Microsoft Docs

2、vue 项目路由配置base(vite.config.js)(注:本人使用vue3.0)

关键代码:base: '/certManage/', (certManage为nginx设置的代理名称,此处为示例)

注:api接口前缀也需要添加/certManage前缀,各位根据各自实际情况配置,此处不做过多描述

import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  
  const alias = {
    // 设置路径
    '~': path.resolve(__dirname, './'),
    // 设置别名
    '@': path.resolve(__dirname, './src')
  }
  if (command === 'serve') {
    // 解决警告You are running the esm-bundler build of vue-i18n.
    alias['vue-i18n'] = 'vue-i18n/dist/vue-i18n.cjs.js'
  }
  return {
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: alias,
      // 导入时想要省略的扩展名列表
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
      dedupe: ['vue']
    },
    css: {
      devSourcemap: true //开发模式时启用
    },
    base: '/certManage/',
    // 打包配置
    build: {
      sourcemap: command === 'build' ? false : 'inline',
      outDir: 'dist', //指定输出目录
      assetsDir: 'assets', //指定静态资源存储目录(相对于outDir)
      // 将js、css文件分离到单独文件夹
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        }
      },
    },
    // vite 相关配置
    server: {
      port: 8887,
      host: true,
      open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: 'http://192.168.10.188:9092/certManage',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/dev-api/, '')
        },
        // '/fileView': {
        //   target: 'http://192.168.10.188:9092/fileView',
        //   changeOrigin: true,
        // },
        // '/msghub': {
        //   target: 'http://localhost:8888',
        //   ws: true,
        //   rewrite: (path) => path.replace(/^\/msgHub/, '')
        // }
      },
    },
  }
})

3、nginx配置

4、net core api接口发布并在IIS中部署(部署略)

5、发布vue项目,并将发布包中的文件拷贝至 api接口发布包下的wwwroot目录下

 

6、启动nginx

7、使用配置的nginx代理地址,在浏览器中访问http://192.168.10.188:9092/certManage 

效果如下:

<think>好的,用户想了解如何整合SSM框架和Vue.js,以及最佳实践。首先,我需要明确SSM指的是Spring、Spring MVC和MyBatis这三个Java后端框架,而Vue.js是前端框架。整合的关键在于前后端分离架构,所以需要解释清楚如何让后端和前端独立开发,通过API接口通信。 接下来,我应该分步骤说明。首先是后端SSM的配置,需要搭建基本的项目结构,配置Spring和MyBatis,确保能提供RESTful API。然后,前端Vue.js部分需要创建项目,配置axios进行异步请求。这里要注意跨域问题,需要说明如何解决,比如CORS配置或者代理设置。 然后是数据交互部分,需要举例说明如何从Vue组件发送GET或POST请求到后端控制器,并处理响应数据。同时,可能需要提到如何封装API请求,比如使用axios的实例或拦截器来统一处理请求和响应。 接着是部署策略,前后端分离后,前端通常会打包成静态资源,部署在Nginx或Tomcat中,而后端则是打包成war或jar运行。需要说明如何配置服务器,确保前端能正确访问后端API。 另外,最佳实践可能包括使用Swagger生成API文档,前后端协作的流程,比如接口定义先行,使用Mock数据进行开发,以及持续集成部署的方法。还有可能涉及安全措施,如JWT认证,如何在Vue中添加拦截器处理token,后端如何校验权限等。 用户可能的问题还包括如何处理跨域、如何管理前端路由与后端Controller的映射,以及如何优化性能,比如前端懒加载,后端缓存策略。需要确保回答覆盖这些点,并提供示例代码,比如Spring的@CrossOrigin注解,Vue的路由配置,以及MyBatis的缓存配置。 最后,生成的相关问题需要引导用户深入思考,比如前后端分离的优势、具体的安全整合方法、性能优化技巧等。确保引用必要的参考资料,比如Spring官方文档或Vue的指南,但用户提供的引用信息有限,可能需要根据现有知识添加合理的引用标识。</think>### SSM框架与Vue.js整合指南 #### 一、架构设计原则 采用**前后端分离架构**,SSM负责提供RESTful API接口,Vue.js负责页面渲染和用户交互。通信使用JSON格式,通过HTTP协议完成数据交互[^1]。 #### 二、整合步骤 1. **后端配置(SSM框架)** ```xml <!-- pom.xml添加Jackson依赖 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency> ``` ```java // Spring MVC配置 @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MappingJackson2HttpMessageConverter()); } } ``` 2. **前端配置(Vue.js)** ```javascript // main.js添加axios import axios from 'axios' Vue.prototype.$http = axios.create({ baseURL: 'http://localhost:8080/api', timeout: 5000 }) ``` 3. **跨域解决方案** ```java // Spring Boot配置类 @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8081") .allowedMethods("*") .allowCredentials(true); } } ``` #### 三、数据交互示例 1. **Vue组件发送请求** ```javascript export default { methods: { fetchData() { this.$http.get('/users') .then(response => { this.userList = response.data }) } } } ``` 2. **Spring控制器响应** ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping public ResponseEntity<List<User>> getAllUsers() { return ResponseEntity.ok(userService.findAll()); } } ``` #### 四、最佳实践 1. **接口文档管理** - 使用Swagger生成API文档 - 添加`springfox-swagger2`依赖 ```java @EnableSwagger2 @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 2. **工程化实践** - 前端使用Vue CLI创建项目 - 后端采用Maven模块化开发 - 部署时前端打包到`dist`目录,通过Nginx部署 3. **安全整合** ```javascript // Vue添加请求拦截器 axios.interceptors.request.use(config => { config.headers.Authorization = localStorage.getItem('token') return config }) ``` ```java // Spring Security配置 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值