前后端分离,springboot项目后台解决跨域,Vue前端Axios操作

1、后台解决跨域问题

前后端分离,遇到跨域问题,java中的解决方案,前端不需要做跨域问题解决,后端去解决跨域问题。
只要在项目中添加一个过滤器就可以了,
前后端分离,springboot项目后台解决跨域,Vue前端Axios操作_第1张图片

代码如下:

package com.example.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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


@Component
@WebFilter(urlPatterns = "/*", filterName = "myFilter")
public class MyFilter1 implements Filter {

    Logger loger = LoggerFactory.getLogger(MyFilter1.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) sResponse;

        response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");

        chain.doFilter(sRequest, sResponse);
    }

    @Override
    public void destroy() {
    }

}

2、Vue前端 Axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

安装

npm install axios

在main.js全局引入

import axios from 'axios'
Vue.prototype.$ajax = axios
Vue.config.productionTip = false

前端界面执行 GET 请求
注意后台路径,端口号后为controller层@RequestMapping(“student”) 名,再加方法名,这里仅供参考

  //在created函数中使用axios的get请求向后台获取用户信息数据
  created() {
    let instance = axios.create();
    instance.defaults.baseURL = "http://localhost:8080";

    instance
      .get("/student/selectAll", {
        params: {
          id:2,
        },
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  },

前端界面执行 POST 请求

后台controller层用@RequestBody注解接收json格式,默认是form格式

前端代码:

created() {
    let instance = axios.create()
    instance.defaults.baseURL = 'http://localhost:8080'

    //在created函数中使用axios的post请求向后台提供信息数据
    let data = { name: 'zhangsan1', age: '21' }
    instance
      .post('/student/insert', data)
      .then((res) => {
        console.log('res=>' + res)
      })
      .catch((res) => {
        console.log('res=>' + res)
      })

    //在created函数中使用axios的post请求向后台提供信息数据
    let data1 = { name: 'zhangsan2', age: '26', id: 2 }
    instance
      .post('/student/update', data1)
      .then((res) => {
        console.log('res=>' + res)
      })
      .catch((res) => {
        console.log('res=>' + res)
      })
  },

后台代码:
主要是说明@RequestBody注解使用

    /**
     * 通过主键更改单条数据
     *
     * @param student
     * @return 单条数据
     */
    @RequestMapping("update")
    public Student update(@RequestBody Student student) {
        return this.studentService.update(student);
    }

    /**
     * 插入单条数据
     *
     * @param student
     * @return 单条数据
     */
    @RequestMapping("insert")
    public Student insert(@RequestBody Student student) {
        return this.studentService.insert(student);
    }

你可能感兴趣的:(spring,boot,filter,过滤器,spring,boot)