springboot+vue + nginx 搭建前后端分离项目

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42912237/article/details/88054539

一.首先得安装node.js

1.进入Node.js官网:https://nodejs.org/en/
在这里插入图片描述
2…验证Node.js是否安装好,在windows下,win+r召唤出运行窗口,输入cmd打开命令行窗口。输入node -v即可得到对应的Node.js版本。
在这里插入图片描述
npm包管理器是集成在Node.js中了,所以在安装Node.js的时候就已经自带了npm,输入npm -v可得到npm的版本。
在这里插入图片描述
输入以下命令npm -g install npm,可以更新npm至最新版本。

二.安装cnpm

1.执行命令 npm install -g cnpm --registry=https://registry.npm.taobao.org ,使用npm的国内镜像(npm 国内镜像 https://npm.taobao.org/)cnpm 命令代替默认的npm命令,增加依赖包加载速度且避免资源限制。

三.cnpm安装脚手架vue-cli

在命令行中运行命令 cnpm install -g vue-cli 安装脚手架。

四.构建项目

1.切换至cd D:\html5\vueProject

输入:

 vue init webpack javalsj-vue

在这里插入图片描述
2.项目下载完成后:
在这里插入图片描述
3.使用idea打开项目
在这里插入图片描述
4.在idea的TerminalTer安装axios

npm install axios -S

在这里插入图片描述
同样的方法安装vue-resource、vuex、jquery、bootstrap,最后还要引入popper.js,不然引入jq报错。

npm install --save popper.js

5.配置main.js,引入所需组件

import Vue from 'vue'
import App from './App'
import router from './router'
import $ from 'jquery'
import Vant from 'vant';
import 'vant/lib/index.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min'
import VueResource from 'vue-resource'
import Vuex from 'vuex'

// 引用axios,并设置基础URL为nginx监听url
var axios = require('axios')
axios.defaults.baseURL = 'https://172.168.10.243:80'
// 将API方法绑定到全局
Vue.prototype.$axios = axios
Vue.use(VueResource);
Vue.use(Vuex);
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

6.配置全局jq
在这里插入图片描述

 // 增加一个plugins
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    })
  ],

在这里插入图片描述
7.配置ip端口号
在这里插入图片描述
8.在components下新建一个vue界面hello.vue,内容如下:

<template>
    <div class="container">
      <p></p>
      <input type="text" id="input">
      <button class="btn btn-info"  @click="hello">按钮</button>
    </div>
</template>

<script>
    export default {
        name: "hello",
      methods:{
          hello(){
            alert($("#input").val());
          },
      }
    }
</script>

<style scoped>

</style>

8.在router的index.js配置hello.vue路由。
在这里插入图片描述
9.运行项目如下表示vue前台搭建完成。
在这里插入图片描述
五.配置nginx
1.下载nginx

2.解压后,打开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;

	#upstream fbm {
    #    server 172.168.11.79:8081;
	#	server 172.168.10.243:8088;
    #}
    server {
        listen       80;
        server_name  172.168.10.243;
		
		#添加头部信息
        proxy_set_header Cookie $http_cookie;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_cookie_domain localhost:8080 172.168.10.243; # 把cookie的path部分从localhost:8080替换成your.domain.name

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
			proxy_pass http://172.168.10.243:8082/;
        }
		location /api/ { #用户
			rewrite  ^/api/(.*)$ /$1 break;
			proxy_pass   http://172.168.10.243:8088/api/;
		}
	

        #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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

六.创建springboot项目
1.配置application.yml

server:
  port: 8088

2.在新建util工具中新建OriginFilter过滤类
在这里插入图片描述

package com.example.util;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ${lcl}
 * @Title: ${NAME}
 * @ProjectName exhibition
 * @Description: TODO
 * @date 2019/2/28 00209:20
 */
@Component
@WebFilter(filterName = "OriginFilter",urlPatterns="/*")
public class OriginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域

        //response.reset();
      /*  response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACES");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");*/
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

3.在controller层新建Hello

package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Hello {
    @RequestMapping(value = "/hello")
    public String sayHello(){
        return "Hello springboot!";
    }
}

4.修改hello.vue
在这里插入图片描述
在这里插入图片描述
5.分别运行前后端项目
在浏览器输入访问地址(通过nginx访问的地址)

172.168.10.243:80

在这里插入图片描述

完成!

展开阅读全文

没有更多推荐了,返回首页