Vue+Axios+Nigix+SpringCloud前端和後端搭建及其碰到的問題

1、Axios、Router的安裝和使用

    一、如何安裝Axios和Router

    1)、進入到工程所在的文件夾,經過cmd指令,進入到window的dos界面html

    2)、輸入:npm install axios --save-dev;來安裝Axios前端

   3)、router在項目建立階段會直接詢問是否安裝,選擇yes便可。vue

    二、如何使用Axios

     1)、專門寫一個index接口js文件,例如:ios

import Axios from 'axios'
import qs from 'qs'


export const User = {
  login(username, password) {
    return Axios.post('/login/',{
      username: username,
      password: password
    })
  },
  addSignUpUser(userInfo) {
    console.log(userInfo)
    return Axios.post('/addUser',userInfo);
  }
}

 2)、在其餘vue控件中引入web

import { User } from '../../api/index'
methods: {
    ...mapMutations(['SET_SIGN_UP_SETP']),
    ...mapActions(['addSignUpUser']),
    handleSubmit (name) {
      const father = this;
      this.$refs[name].validate((valid) => {
        if (valid) {

          const userinfo = {
            username: this.formValidate.name,
            password: this.formValidate.password,
            mail: this.formValidate.mail,
            phone: this.$route.query.phone
          };
          //this.addSignUpUser(userinfo);
          User.addSignUpUser(userinfo)
            .then(result =>{
              if (result.status) {
                this.$Message.success('註冊成功');
                father.SET_SIGN_UP_SETP(2);
                this.$router.push({ path: '/SignUp/signUpDone' });
              } else {
                this.$Message.error('註冊失敗');
              }
            });
        } else {
          this.$Message.error('註冊失敗');
        }
      });
    }
  },

    三、Axios跨域問題如何解決?

   

  1)、這裏以訪問api/addUser爲例,直接訪問以下:spring

  

Axios.post("http://www.happymall.com/api/addUser")
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})

  Step1:配置BaseUrlvue-router

   在main.js中,配置下咱們訪問的Url前綴:數據庫

import Vue from 'vue'
import App from './App'
import Axios from 'axios'

Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api'
Axios.defaults.headers.post['Content-Type'] = 'application/json';

Vue.config.productionTip = false

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

關鍵代碼是:Axios.defaults.baseURL = '/api',這樣每次發送請求都會帶一個/api的前綴。npm

Step2:配置代理json

修改config文件夾下的index.js文件,在proxyTable中加上以下代碼;示意圖以下:

'/api':{
    target: "http://www.happymall.com",
    changeOrigin:true,
    pathRewrite:{
        '^/api':''
    }
}

 

Step3:修改請求Url

修改剛剛的axios請求,把url修改以下:

this.$axios.get("/addUser")
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})

Step4:重啓服務

重啓服務後,此時已經可以訪問了。

原理:

由於咱們給url加上了前綴/api,咱們訪問/api/addUser就當於訪問了:localhost:8080/api/addUser(其中localhost:8080是默認的IP和端口)。

在index.js中的proxyTable中攔截了/api,並把/api及其前面的全部替換成了target中的內容,所以實際訪問Url是http://www.happymall/api/addUser。

四、路由如何使用

 1)、全局引入路由

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

2)、配置路由規則

import Vue from 'vue';
import Router from 'vue-router';
import Index from '@/components/Index';
const Login = resolve => require(['@/components/Login'], resolve);
const SignUp = resolve => require(['@/components/SignUp'], resolve);

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/', // 首頁
      name: 'Index',
      component: Index
    },
    {
      path: '/Login', // 登陸
      name: 'Login',
      component: Login
    },
    {
      path: '/SignUp', // 註冊
      /*name: 'SignUp',*/
      component: SignUp,
      children: [
        {
          path: '/',
          name: 'index',
          component: CheckPhone
        },
        {
          path: 'checkPhone',
          name: 'CheckPhone',
          component: CheckPhone
        },
        {
          path: 'inputInfo',
          name: 'InputInfo',
          component: InputInfo
        },
        {
          path: 'signUpDone',
          name: 'SignUpDone',
          component: SignUpDone
        }
      ]
    },
 ]
});

3)、使用路由

 User.addSignUpUser(userinfo)
            .then(result =>{
              if (result.status) {
                this.$Message.success('註冊成功');
                father.SET_SIGN_UP_SETP(2);
                this.$router.push({ path: '/SignUp/signUpDone' });
              } else {
                this.$Message.error('註冊失敗');
              }
            });

2、Nigix路由地址問題

    在Nigix經過配置服務器,將前端請求經過路由機制並結合SpringCloud實現負載均衡;服務器配置以下:

server {
        listen 80; server_name www.happymall.com;
        location /{
            root happymall;
            index index.html;
        }
                
        location /api {
            proxy_pass http://127.0.0.1:9005/zuul-user/user/manage;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Origin' '*'; 
        }
        
    }

http://api.douban.com/api/addUser發送的請求,經過路由機制能夠將該請求發送到Zull客戶端;實現負載均衡。

http://127.0.0.1:9005/zuul-user/user/manage;

3、Zull客戶端和Euraka服務器的配置

 一、創建Euraka服務器

  配置文件以下:

server.port=8761
#eureka config
spring.application.name=eureka-server
eureka.instance.hostname=localhost
eureka.client.registerWithEureka=true
eureka.client.fetchRegistry=true
eureka.instance.preferIpAddress=true
eureka.server.enable-self-preservation=false

二、創建Zull客戶端

配置文件以下:

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
server.port=9005
spring.application.name=serviceZuul
zuul.routes.zuul-user.path=/zuul-user/**
zuul.routes.zuul-user.serviceId=userservice

zuul.sensitive-headers=

 三、訪問Euraka服務器查看微服務

 

4、springcloud微服務搭建

 一、先創建一個父工程

  先創建一個父工程,裏面只保留一個pom.xml文件,用來提供繼承服務,使其餘微服務都繼承該父工程;統一spring包的版本。

 二、創建一個公共資源工程

  繼承父工程,並用於提供公用的pojo,vo和utils工具類;

三、創建一個respositry公共工程

  該工程用來提供數據庫鏈接池

四、將項目進行縱向切分,分紅不一樣的微服務,並分別創建Maven工程

 以用戶管理模塊爲例,將該模塊創建一個微服務;整體項目架構以下所示:

五、編寫user微服務的代碼

    根據MVC模型,編寫Controller、Modle和View層代碼,其中controller層的代碼示例以下

  

package cn.tedu.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.common.pojo.User;
import cn.tedu.common.vo.SysResult;
import cn.tedu.user.service.UserService;

@RestController
@RequestMapping("/user/manage")
public class UserController {
@Autowired
private UserService userService;
    @RequestMapping("/checkUserName")
    public SysResult checkUserName(String userName) {
        Integer exist = userService.checkUsername(userName);
        //根據exist判斷返回結果
        if(exist == 0) {
            return SysResult.ok();
        } else {
            return SysResult.build(201, "已存在", null);
        }
    }
    
    @RequestMapping("/addUser")
    public SysResult userSave(@RequestBody User user) {
        try {
            userService.userSave(user);
            return SysResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.build(201, e.getMessage(), null);
        }
        
    }
}

由於前端傳遞的格式是Json字符串格式,所以在後端中接受對象時,要加上@RequestBody;表示該請求參數是一個對象。

5、postman測試效果以下圖所示:

相關文章
相關標籤/搜索