天天看點

springboot+vue.js前後端分離架構:VueJs請求springboot背景

VUE前端:

1.安裝好npm環境

2.檔案目錄:

springboot+vue.js前後端分離架構:VueJs請求springboot背景

3.建立vue頁面:

代碼:

<template>
  <div class="login">
    {{ message }}<br/>
    <input v-model="username" placeholder="使用者名"><br/>
    <input v-model="password" placeholder="密碼"><br/>
    <button v-on:click="login">登陸 </button>
  </div>
</template>

<script>
    export default {
      name: "login",
      data() {
        return {
          message: 'Vue 8081 登陸頁面',
          username: '',
          password: ''
        }
      },
      http: {
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
      },
      methods: {
        login: function () {
          var _this = this;
          console.log(_this.username+_this.password);
          _this.$http.post('http://localhost:8080/oneController/one', {
                username: _this.username,
                password: _this.password
          },{emulateJSON:true}
          )
            .then(function (response) {
              var errorcode = response.data.code;
              if (errorcode == "200") {
                _this.$router.push(
                  { path: '/HelloWorld',
                    query: {
                      user: response.data.data,
                    }
                  });
              } else {
                _this.$router.push({ path: '/Fail' });
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      }

    }
</script>

<style scoped>

</style>
           

4.main.js增加路由子產品

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//-------------增加路由子產品------------------
import  VueResource  from 'vue-resource'

//import iView from 'iview'
Vue.use(VueResource);
Vue.config.productionTip = false

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

Springboot背景:

1.搭建完整的架構SSM

2.CorsConfig.java 請求頭編碼過濾

package com.usermodule.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

 /**
  * @ClassName: CorsConfig 
  * @Description: 跨域系統配置
  * @author Bob Zhang 
  * @date 2019年1月15日 下午4:11:14 
  */
@Configuration
public class CorsConfig {
    /**
     允許任何域名使用
     允許任何頭
     允許任何方法(post、get等)
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // // addAllowedOrigin 不能設定為* 因為與 allowCredential 沖突,需要設定為具體前端開發位址
        corsConfiguration.addAllowedOrigin("http://localhost:8081");//前端的開發位址 允許跨域通路的域名
        corsConfiguration.addAllowedHeader("*");	// 請求頭
        corsConfiguration.addAllowedMethod("*");	//請求方法 
//        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
//        corsConfiguration.addAllowedMethod(HttpMethod.POST);
//        corsConfiguration.addAllowedMethod(HttpMethod.GET);
//        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
//        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
//        corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
        
        // 預檢請求的有效期,機關為秒。
       // corsConfiguration.setMaxAge(3600L);
        // allowCredential 需設定為true
        corsConfiguration.setAllowCredentials(true);
        
        return corsConfiguration;
    }

    @Bean	
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
           

3.controller類

package com.usermodule.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.usermodule.model.UserModel;
import com.usermodule.service.oneService;

@Controller 
//@RestController  @RestController注解相當于@ResponseBody +@Controller合在一起的作用。
//或者在注解上加@ResponseBody
@RequestMapping("oneController")
public class oneController {
    @Autowired
    private oneService oneService;
	
	
	@RequestMapping("/one")
	public UserModel home(){
		System.out.println("1234");
	//	UserModel user = oneService.one();
		UserModel user = new UserModel();
		return user;
	}
	
}
           

繼續閱讀