Springboot-Vue跨域請求(詳細)


新建Vue項目codeduck-vue

項目目錄結構(主要文件)

|src
|———App.vue			# 根組件
|———assets
|——————logo.png		# Vue logo
|———components
|——————Home.vue		# 歡迎頁面
|——————Login.vue	# 登錄頁面
|———main.js			# 程序入口文件,用來加載各種公共組件
|———router
|——————index.js		# 路由
|vue.config.js		# vue配置文件

在項目內安裝axios並配置

  1. 安裝 axios npm install --save axios

  2. main.js中引入axios並配置

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import axios from 'axios'
    
    // 前端請求默認發送到 http://localhost:8848
    axios.defaults.baseURL = 'http://localhost:8848'
    // 全局注冊,之后可在其他組件中通過 this.$axios 發送數據
    Vue.prototype.$axios = axios
    
    Vue.config.productionTip = false
    
    new Vue({
      router,
      render: h => h(App)
    }).$mount('#app')
    
    
  3. 配置vue.config.js

    module.exports = {
      devServer: {
        // 反向代理端口地址及端口為 http://localhost:8080
        proxy: 'http://localhost:8080',
        port: 8848
      }
    }
    

Login.vue 登錄頁

<template>
  <div>
    用戶名:<input type="text" v-model = "loginForm.username" placeholder="請輸入用戶名">
    <br><br>
    密碼:<input type="text" v-model = "loginForm.password" placeholder="請輸入用戶名">
    <br><br>
    <button v-on:click="login">登錄</button>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: 'codeduck',
        password: '123123'
      },
      responseResult: []
    }
  },
  methods: {
    login () {
      // 使用 axios發送請求
      this.$axios.post('/login', {
        username: this.loginForm.username,
        password: this.loginForm.password
      }).then(successResponse => {
        if (successResponse.data.code === 200) {
          this.$router.push('/index')
        }
      }).catch(failResponse => {
        console.log('登錄失敗')
      })
    }
  }
}
</script>

<style scoped>

</style>

Home.vue 歡迎頁

<template>
  <div>
    <h1>Hello</h1>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>

<style scoped>

</style>

index.js 路由配置

import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/index',
    name: 'Home',
    component: Home
  }
]

const router = new VueRouter({
  routes
})

export default router

App.vue 根組件掛載路由

<template>
  <div id="app">
    <!--路由占位符-->
    <router-view></router-view>
  </div>
</template>

<script>
</script>

<style>
</style>

啟動項目 npm run server

訪問地址 http://localhost:8848/

image-20200726125154116

新建SpringbootWeb項目

新建項目codeduck並勾選web組件

新建pojo——user

public class User {

    int id;
    String username;
    String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

新建Result類用於封裝返回信息

public class Result {

    //響應碼
    private int code;

    public Result(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

}

新建配置類CorsConfig用於跨域請求

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }
}

新建controller類

@Controller
public class LoginController {

    @PostMapping(value = "/login")
    @ResponseBody
    public Result login(@RequestBody User user) {

        String username = user.getUsername();
        String password = user.getPassword();
        if (username.equals("codeduck") || password.equals("123123")){
            return new Result(200);
        }else {
            return new Result(400);
        }
    }
}

yaml配置

server:
  port: 8080

啟動springboot項目

點擊前端頁面登錄按鈕即可跳轉到歡迎頁

image-20200726125258464


免責聲明!

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



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