SpringBoot + Vue + nginx項目部署(零基礎帶你部署)


一、環境、工具

jdk1.8

maven

spring-boot

idea

VSVode

vue

百度網盤(vue+springboot+nginx源碼):

鏈接:https://pan.baidu.com/s/1m3ciEUmUsjqoQBnIJBR7Zw
提取碼:6gi9 

二、搭建后台spring-boot框架

步驟:

1、new- project選擇Spring Initializr  next

2、創建項目文件結構以及jdk版本

3、選擇項目需要的依賴

next然后finish

4、創建完畢的文件結構如圖

5、對pom.xml更改,信息如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.zks</groupId>
    <artifactId>myspringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>myspringboot</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
 
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <!-- 分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- alibaba的druid數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
                <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>
    </dependencies>
 
        <build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
 
</project>
pom.xml

注意:本項目用是連接oracle,使用其他數據庫的請自行使用數據庫連接dependency

6、在resources文件夾下刪除application.properties文件並添加新的application.yml文件,信息如下

server:
  port: 8080
spring:
  datasource:
#    url: jdbc:oracle:thin:@192.168.153.2:1521:orcl
    username: admin
    password: 123
    driver-class-name: oracle.jdbc.driver.OracleDriver
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp
mybatis:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    mapUnderscoreToCamelCase: true
    logImpl: org.apache.ibatis.logging.stdout.StdOutImpl

7、更改項目啟動類(DemoApplication)

package com.zks.myspringboot;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("com.zks.dao")
public class MyspringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyspringbootApplication.class, args);
    }
 
}

右鍵運行啟動類(DemoApplication),就可以成功啟動

 

注意:可能會遇到一個問題:Unable to import maven project: See logs for details

maven版本過高3.6.2及以上可能也會出現該情況,就要降低版本了,我將3.6.3 -> 3.6.1版本重新編譯,成功!

3.6.1下載:

鏈接:https://pan.baidu.com/s/1Q9yN-mS8TVZEn7y41IOsXw
提取碼:l2fz

 

項目結構請模仿此圖

為了證明成功啟動springboot,我們在controller寫個main類,return一個頁面,然后瀏覽器看看

package com.example.jzcx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping(value = "/a/")
@Controller
public class Main {

    @RequestMapping(value = "index")
    public String main(){
        return "index";
    }
}

因為我們在application.yml文件設端口為8080,瀏覽器訪問:localhost:8080/a/index,即可看到頁面

到這里后端springboot就寫完了!

三:前端vue搭建

1. 打開cmd:npm init webpack jzc

搭建起來的項目結構如圖:

 

2. vue中axios跨域請求后端接口

一,首先在文件中下載axios

cnpm install axios --save-dev

二、在main.js中引入及獲取對象

 import Vue from 'vue'

import Axios from 'axios'

Vue.prototype.$axios = Axios 

三、在config里面的index.js文件里設置proxyTable

const path = require('path')
 
module.exports = {
  dev: {
 
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/': {
        target: 'http://localhost:8080',//此處可以換成自己需要的地址
        changeOrigin: true,
        pathRewrite: {
          '^/': ''
        }
     }
    },

此處的8080對應application.yml文件中的

 四、main.js里添加host

 Vue.prototype.HOST = "/" 

五、數據請求

        
import qs from 'qs';

this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({ page:1, limit:2 })).then(res =>{ // console.log(res.data); this.totalNum = res.data.count; this.dataList = res.data.dataList; this.redOrBlack = res.data.redOrBlack; loading.close(); })

如果不加上qs.stringify,axios默認請求會帶上花括號,后端就拿不到前端傳過來的參數,使用qs庫去掉花括號

qs使用:

 npm install qs --save-dev 

 import qs from 'qs'; 

注意:配置文件后,要重新啟動哦!!!

到這里就可以使用axios

 3. vue中使用jquery庫

 一、npm install jquery --save-dev 

還要在引入popper.js,不然jq引入報錯,兩者有一定的關聯

 二、npm install popper.js --save-dev 還是 npm install popper --save-dev 

都試一下

三、配置main.js,引入所需組件

 import $ from 'jquery' 

 

 在webpack.base.conf.js最上面引入

  const webpack = require('webpack') 

 

結果配置好了,npm run dev,webpack報錯引入jQ時發生“'$' is defined but never used”

 

 解決:注釋掉webpack.base.conf.js里的這段:

 

 重新 npm run dev即可運行,這樣jquery也可以使用了 

4.使用scss預編譯

一、首先安裝依賴

 npm install node-sass sass-loader --save-dev 

其中的sass-loader我安裝的時候是8.0.0,但是安裝完后報錯,好像是說版本太高,和其他不兼容,於是我就降低版本sass-loader:7.3.1、node-sass:4.13.0。

 

如果出現錯誤,可以嘗試使用淘寶鏡像安裝解決:

 npm install -g cnpm --registry=https://registry.npm.taobao.org (安裝淘寶鏡像) 

然后使用cnpm 代替npm 安裝node-sass和sass-loader。
安裝好之后就可以在你的.vue文件中使用了:

二、找到buildwebpack.base.conf.js,在rules中添加scss規則

 { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } 

 在vue文件中使用

  <style lang='scss'> </style> 

 4.1 在vue項目全局中引入scss

 全局引用時需要安裝sass-resources-loader

  npm install sass-resources-loader --save-dev 

 修改build中的utils.js

 簡單就是修改scss、sass使用的方法,將原本的generateLoaders方法換成自定義的generateSassResourceLoader方法即可

 

 然后添加一個方法generateSassResourceLoader()

 generateSassResourceLoader代碼如下:

  function generateSassResourceLoader() {
    var loaders = [
      cssLoader,
      'sass-loader',
      {
        loader: 'sass-resources-loader',
        options: {
          // 多個文件時用數組的形式傳入,單個文件時可以直接使用 path.resolve(__dirname, '../static/style/common.scss'
          resources: [resolveResource('theme.scss')]  
        }
      }
      ];
      if (options.extract) {
        return ExtractTextPlugin.extract({
          use: loaders,
          fallback: 'vue-style-loader'
          
        })
      } else {
        return ['vue-style-loader'].concat(loaders)
      }
    }

還要再修改樣式的路徑,如下:

 

 

然后在src下面新建style文件夾下再新建theme.scss即為全局scss文件

 

 到這里scss配置完成,還可以在vue文件引入我們theme.scss全局樣式

5. 使用element-ui

因為要做分頁,本來想使用layui的分頁,但是好像vue要引入layui不能npm i的,vue對layui好像不是很支持,於是使用餓了么UI

安裝: npm i element-ui --save-dev 

在main.js中引入

import ElementUI from 'element-ui' //element-ui的全部組件

import 'element-ui/lib/theme-chalk/index.css'//element-ui的css

Vue.use(ElementUI) //使用elementUI 

使用elementui的分頁也很簡單

<div class="block">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page.sync="currentPage"
                            :page-size="2"
                            layout="prev, pager, next"
                            :total="totalNum"
                            >
                        </el-pagination>
                    </div>

 

export default {
  name: 'RedOrBlack',
  data () {
    return {
        currentPage: 1,
        totalNum:1,
        dataList:[],
        fullscreenLoading: false
    }
  },
  created(){
      const loading = this.$loading({
          lock: true,
          text: '拼命加載中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({
              page:1,
              limit:2
          })).then(res =>{
            //   console.log(res.data);
              this.totalNum = res.data.count;
              this.dataList = res.data.dataList;
              this.redOrBlack = res.data.redOrBlack;
              loading.close();
          })

        $('.list-group').css('display','block');
        $('.content-table').css('display','none');
  },
  methods:{
    handleSizeChange(val) {
        console.log(`每頁 ${val} 條`);
    },
    handleCurrentChange(val) {
// 點擊上下頁都會觸發這個函數,所以在此函數寫請求后端返回數據
        const loading = this.$loading({
          lock: true,
          text: '拼命加載中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({
            redOrBlack:this.redOrBlack,
            corpName:this.corpName,
            page:val-1,
            limit:2
        })).then(res =>{
            // console.log(res.data);
            this.totalNum = res.data.count;
            this.dataList = res.data.dataList;
            this.redOrBlack = res.data.redOrBlack;
            this.currentPage = val;
            loading.close();
        })
    }

建議直接觀看官網,講的很詳細:https://element.eleme.cn/#/zh-CN/component/pagination

因為我要自定義餓了么的分頁樣式,於是有個坑要踩一下(餓了么的element-ui修改樣式后不生效)

不能直接在組件中直接寫餓了么樣式,因為單組件有scoped,所以需要在app.vue中直接定義餓了么分頁樣式寫,注意<style>不能加scope!

開發中在App.vue上寫全局樣式,餓了么分頁可以修改,但我打包部署后,在app.vue上修改的樣式(餓了么分頁)無效,於是只能修改內部插件的樣式,

在node_modules\element-ui\lib\theme-chalk\index.css下修改,其他文件修改了無效的,再次打包部署樣式已發生變化。$message提示框修改也是在index.css下修改,同個道理

6. vue中引入echarts,柱形圖沒有顯示數據(圖已經出來了,就是沒數據)

把this.drawBarChart(); 寫在created生命周期中請求后端拿數據成功時加上,然后drawBarChar()方法就寫在methords方法中,echarts要注意異步的問題,數據還沒請求成功 圖表已經初始化完了 所以圖表渲染不了獲取到的數據,也可以試一下把ajax和初始化圖標都放在mounted里;也有一些情況是this的指向有問題,所以數據undefined。

最后發現我圖已經出來了,但是沒顯示數據,是因為option.series.[0].data接收的是數組,而我卻給他傳個字符串,最后轉為數組就正常顯示了,大家傳數據千萬要看清楚接收的參數類型,不要像我一樣,搞了很久才發現類型不對。

到這里我們的開發就開發完成了,現在進行項目的部署,使用nginx部署服務器

7. nginx

一、nginx下載:http://nginx.org/download/nginx-1.12.2.zip

二、vue項目打包,拷貝dist下的static和index.html到/usr/local/nginx/html目錄下

三、打開/usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        
         # 靜態資源目錄,即vue打包后的dist里的靜態資源
        root  /usr/local/nginx/html;
        index  index.html index.htm;
        
        # 后端服務的配置
        
        location /Jzcx/ {
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                # 后端服務地址
                 proxy_pass http://localhost:8080;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }



}
nginx.conf

四、Java項目打包上傳到 服務器,開啟服務

因為springboot是基於manev,所以生成jar包

打開cmd,先進入后端項目目錄,執行mvn clean先清除一下編譯文件,再重新生成mvn package,在target文件夾下有個jar包

java -jar *****.jar --server.port=8080

后端服務成功開啟

五、打開cmd,先進入nginx目錄下,執行nginx.exe

注:執行nginx.exe可能會報錯,unknown directive "鍩? in F:\nginx/conf/nginx.conf:3,因為改nginx.conf這個文件配置的時候用記事本改的,於是記事本會自動在文件中添加BOM頭,所以我們使用notepad++去除BOM頭

 

 

這樣就部署好了,前端用的是8081,在nginx下配置的

server {   listen       8081;}

后端在jar包那執行用的是8080,在nginx下也要請求后端的接口,要一一對應。

注:若想關閉nginx.exe,直接關閉cmd是關不掉的,需要再打開cmd窗口,進入nginx下執行nginx -s stop停止服務。

前端8081,后端8080,瀏覽器輸入localhost:8081即可看到頁面。

8. elementUI圖標打包部署后404

結果啟動項目之后發現餓了么的圖標不顯示,說404找不到這個資源,dev下正常,build圖片顯示不出來,

查看網絡請求可以看到如下兩個字體文件加載不到:

 http://localhost:59090/static/css/static/fonts/element-icons.535877f.woff

 http://localhost:59090/static/css/static/fonts/element-icons.732389d.ttf 

問題原因

查看 /build/webpack.base.conf.js 文件可以發現,woff 或 ttf 這些字體會經由 url-loader 處理后在 static/fonts 目錄下生成相應的文件。

 也就是說實際應該通過 /static/fonts/** 路徑來獲取字體圖標,而實際卻是請求 /static/css/static/fonts/**,自然報 404 錯誤。

解決辦法

打開 build/utils.js 文件,在如下位置添加 publicPath: '../../';

 

修改完畢后重新 build 發布,可以發現圖標已經可以正常顯示了。

到目前為止,訪問localhost:8081/#/index即可看到頁面

1)路由url上必須帶上#號

2)刷新可以繼續留在當前訪問的頁面

3)域名后面可以加路由

 

因為我的vue的路由是有個#號的,也就是router並不是history模式,所以只要設置模式為history模式就可以去除#

 

問題所在:但是你刷新子路由頁面,你會發現報404?

分析:前端路由找不到,然后就跑去后端的接口請求,結果也是404,這個404是后端發送的,並非前端發送,

很簡單你在瀏覽器沒有加載js的時候直接輸入這個帶路由的url會被發送到服務器端,服務器又不認識這個路由,所以就出現404了。

一般的解決方案都是在服務器把找不到的路由指到index.html(vue頁面)。這樣在vue-router初始化好之后就會跳到相應的路由頁面。

這個帶來的問題就是404頁面不會出現了,所以可能要在前端處理好404.

官方文檔:https://router.vuejs.org/zh-cn/essentials/history-mode.html

所以刷新子路由報404,因為在nginx部署那里修改配置文件

nginx下增加try_files $uri $uri/ /index.html;

 location / {

    root html;

    index index.html index.htm;

    try_files $uri $uri/ /index.html;

}

# 靜態資源目錄,即vue打包后的dist里的靜態資源

root /usr/local/nginx/html;

index index.html index.htm; 

重新運行nginx,現在在子路由刷新已不會報404錯誤。

現在修改后訪問:localhost:8081

1)去除#號

2)刷新可以繼續留在當前訪問的頁面

3)域名后面不可以加路由

 

 

能把springboot+vue+nginx部署上線,非常感謝以下文章作者

搭建spring-boot+vue前后端分離框架並實現登錄功能:https://blog.csdn.net/zks_4826/article/details/81603865

vue中axios跨域請求解決:https://blog.csdn.net/srttina/article/details/83309512

webpack構建Vue項目引入jQ時發生“'$' is defined but never used”的處理:https://www.cnblogs.com/chig/p/10432210.html

在vue項目中使用scss:https://www.jianshu.com/p/0b604429b0d5

nginx安裝及使用:https://www.cnblogs.com/jiangwangxiang/p/8481661.htmlhttps://blog.csdn.net/qq_22027637/article/details/81777562

vue項目在linux中,springboot項目在本地,使用nginx部署:https://blog.csdn.net/weixin_40331613/article/details/81329277

啟動nginx.ex錯誤:unknown directive "鍩? in F:\nginx/conf/nginx.conf:3:https://www.cnblogs.com/jstarseven/p/4683679.html、解決方案(notepad++設置默認為UTF-8無BOM格式):https://jingyan.baidu.com/article/335530da87451819cb41c3da.html

Vue.js - 解決部署到服務器后Element UI圖標不顯示問題(404錯誤):https://www.hangge.com/blog/cache/detail_2473.html#

vue開發,在子路由里的時候刷新頁面,頁面就找不到了:https://segmentfault.com/q/1010000008771041/a-1020000008771211

vue 除去#符號,並部署后瀏覽器刷新不出現404錯誤處理:https://blog.csdn.net/laozhong110/article/details/80999429https://blog.csdn.net/bocongbo/article/details/81670072

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM