美文网首页前端Vue专辑
Vue和spring boot跨域笔记

Vue和spring boot跨域笔记

作者: 圈圈猫 | 来源:发表于2019-01-29 16:54 被阅读2次

说实话,刚开始学习vue,然而我对js也是一知半解,是指在运用而已,看着前端大佬写的一手好vue,自己也想试试,而且到处都能耍有种feel一般的感觉,于是自己也想搞,刚开始就遇到这个问题很尴尬,就只能百度找方案,也好做个笔记为后面复习用。

1、新建一个vue项目

这个新建项目我就不再这里说了,大佬们都给出了不同的方式新建。

2、在src目录下新建一个axios.js文件

image.png

3、封装axios网络框架

import axios, {AxiosInstance as router} from 'axios'

//请求超时时间
axios.defaults.timeout = 5000
//请求地址
axios.defaults.baseURL = 'http://127.0.0.1:15588'

axios.interceptors.request.use(
  config => {
    config.data = JSON.stringify(config.data)
    //在这里添加请求头数据
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    return config
  }, error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(responce => {
//如果返回的码是2就跳转到登录页面,说明页面过期了
  if (responce.data.errCodes === 2) {
    router.put({
      path: '/login',
      query: {redirect: router.currentRoute.fullPath}
    })
  }
  return responce
},
error => {
  return Promise.reject(error)
})

export function fetch (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params: params})
      .then(responce => {
        resolve(responce.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      })
  })
}

4、在main.js中引用(注释写了作用)

import Vue from 'vue'
import App from './App'
import router from './router'     //路由
import ElementUI from 'element-ui'     //element脚手架
import {fetch, post} from './api/axios'   //这里就写了两种方式(fetch)get 和post方式

Vue.config.productionTip = false

Vue.prototype.$fetch = fetch
Vue.prototype.$post = post

Vue.use(ElementUI)

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

5、在Helloworld.vue中访问服务器

<template>
  <div class="hello">
    <div>
      <h1>用户管理</h1>
    </div>
    <div class="ssss">
      <template>
        <el-table
          :data="tableData"
          :border="true"
          :stripe="true"
          style="width: 100%;"
          v-loading="loading2" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-table-column
            property="id"
            label="编号"
            width="180"
          :align="center">
          </el-table-column>
          <el-table-column
            property="name"
            label="姓名"
            width="180">
          </el-table-column>
          <el-table-column
            property="age"
            label="年龄"
            width="180">

          </el-table-column>
          <el-table-column
            property="password"
            label="密码"
            width="180">
          </el-table-column>

        </el-table>
      </template>
    </div>
    <div class="pagina">
      <el-pagination
        background
        :layout="prev, pager, next"
        :total="1000">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      tableData: [{
        id: '1',
        name: '哇啊啊啊',
        age: 17,
        password: '1111'
      }, {
        id: '1',
        name: '哇啊啊啊',
        age: 17,
        password: '1111'
      }],
      loading2: true,
      oneTime: 1000
    }
  },
  created () {
    this.shows()
  },
  methods: {
    async shows () {
      //访问服务端获取用户表
      this.$fetch('/getUser').then((res) => {
        const userList = res.data
        this.tableData = []
        if (!userList) {
          return
        }
        userList.forEach(item => {
          const user = {}
          user.name = item.name
          user.id = item.id
          user.age = item.age
          user.password = item.password
          this.tableData.push(user)
          this.loading2 = false
        })
      })
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  @import url("//unpkg.com/element-ui@2.4.11/lib/theme-chalk/index.css");
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
  .ssss{
    display: inline-flex;
    margin-top: 20px;
  }
  .pagina{
    margin-top: 40px;
  }
</style>

6、在spring boot服务端添加过滤条件

import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}

6、服务端的controller

@RestController
@Slf4j
public class UserController {

    @Autowired
    UserService service;

    /***
     * 查询用户
     * */
    @RequestMapping("/getUser")
    public ResultVO getUser(){

        return ResultVOUtils.success(service.findAll());
    }
}

7、数据库的数据就自己造可以了,用mysql数据库直接插入几条数据。也可以自己写代码插入或者写脚本插入都行。

image.png

到这里就可以启动spring boot服务和vue服务,然后在浏览器中输入地址http://127.0.0.1:8080试试看,这是我刚开始vue,spring boot也不轻不楚的,还希望大佬能指正下,欢迎大佬们吐槽。

相关文章

  • SpringBoot+Vue数据交互

    后端框架Spring Boot,前端框架vue 1. 跨域+携带cookie 跨域-携带cookie 2. 拦截器...

  • 跨域配置

    SpringBoot跨域配置 我们的后端使用Spring Boot。Spring Boot跨域非常简单,只需书写以...

  • Vue和spring boot跨域笔记

    说实话,刚开始学习vue,然而我对js也是一知半解,是指在运用而已,看着前端大佬写的一手好vue,自己也想试试,而...

  • 2019-04-01

    Spring Boot轻松跨域:Spring Boot中采用注解轻松实现跨域的一个基础例子 1.项目结构,conf...

  • spring boot http 转 https (配置http

    我的项目是前后端分离的项目,后端spring boot 前端vue,vue的跨域是用nginx代理的。 这里先介绍...

  • Spring Boot 跨域访问

    如何在 Spring Boot 中配置跨域访问呢?Spring Boot 提供了对 CORS 的支持,您可以实现W...

  • spring boot + VUE跨域处理

    在使用 vue 做前端开发时,碰到 vue 请求接口出现跨域问题。解决的方法,就在后台添加一个跨域请求的过滤器,来...

  • Spring boot2.4版本跨域问题

    问题描述 spring boot2.4版本之后,延用2.3的跨域方式,访问swagger出错. 2.3版本跨域配置...

  • Ajax跨域问题复现及解决方法(学习笔记)

    模拟跨域问题 1.创建后台项目 使用SPRING BOOT开发网址如下 https://start.spring....

  • Spring Boot打war包部署遇到的坑

    Spring Boot解决跨域问题 在Controller层加入@CrossOrigin注解即可 部署 pom.x...

网友评论

    本文标题:Vue和spring boot跨域笔记

    本文链接:https://www.haomeiwen.com/subject/ignbjqtx.html