The most comprehensive front-end axios and back-end cross-domain configuration processing in history – Xu Guoguoah

Article Directory

    • The most comprehensive front-end axios and back-end cross-domain configuration processing in history
        • Installing axios [https://www.axios-http.cn/]
          • Package a basic request js
          • Create a remote.ts or other file name
        • Use
      • Vite Resolve Cross-Domain Issues
          • Problem solving
            • Create a new vite.config.js file in the root directory of the project folder and write the code:
            • You can then request data across domains by writing in the file that needs to send the request:
    • Cross-domain processing related to backend SpringBoot
      • I. Why cross-domain problems occur
          • Same Source Policy
      • II. What is Cross-domain
            • Example:
      • III. Non-Same Source Restrictions
        1. How the java backend implements cross-domain requests
          • For cross-domain requests of CORS, the following modes are available:
            • Note
        • 1.Return New CorsFilter(Global Cross-Domain)
        • 2. Rewrite WebMvcConfigurer(Global Cross-Domain)
        • 3.Using annotations(Local Cross Domain)
            • Use annotation @CrossOrigin: on method
        • 4. Manually setting the response header(Local Cross Domain)
        • 5. Cross domain with custom filter
            • First, write a filter with the name MyCorsFilter.java.
            • Configure this filter in web.xml to take effect
          • Springboot simplifies
            • Used in SpringBoot
            • Axios get Request
            • Axios post Request
    • Summary

The most comprehensive front-end axios and back-end cross-domain configuration processing in history

The content of this section needs to bevueMaster the front-end framework and the basic framework of the back-end!The separation of front-end and back-end projects often involves the issue of cross-domain requests.,Let’s master it today!!!

Installing axios [https://www.axios-http.cn/]
npm install axios 
Package a basic request js
Create a remote.ts or other file name
import axios from "axios";
const server = 'http://localhost:8181'

/**
 * async Asynchronous processing
 * await Wait for processing to complete
 */
async function getData(url,param){
    var ret = ''
    await axios.get(server+url, {params: param}).then(function (res) {
        ret = res.data
    })
    return ret
}

//postRequest body transfer data
async function postData(url,param){
    var options = {  // set upaxiosParameters
        url: server+url,
        data: param,
        method: 'post',
    }

    var ret = ''
    await axios(options).then(function (res) {
        ret = res
    })
    return ret
}

//postSubmit form Request header transfer data
async function postDataForm(url,param){
  var options = {  // set upaxiosParameters
    url: server+url,
    data: param,
    method: 'post',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}
  }

  var ret = ''
  await axios(options).then(function (res) {
    ret = res
  })
  return ret
}


async function uploadFile(url,param){
    var options = {  // set upaxiosParameters
        url: server+url,
        data: param,
        method: 'post',
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    var ret = ''
    await axios(options).then(function (res) {
        ret = res.data
    })
    return ret
}

// export:Export variables、function
export  {getData,postData,postDataForm,uploadFile} 
Use
import {getData,postData,uploadFile} from '../common/remote'

getData('/user/list',{current:current}).then(function (res) {

})

postData('/user/delete',[id]).then(function (res) {

})

uploadFile(url,formData).then(function (res) {

}) 

Vite Resolve Cross-Domain Issues

Access-Control-Allow-Origin

  • The cross-domain problem occurs when the code is written.
Problem solving
Create a new vite.config.js file in the root directory of the project folder and write the code:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],

  server:{
    proxy: { 
      '/api': {
        target: 'http://localhost:8080/',  //The URL you want to visit across domains
        changeOrigin: true,   // Allow cross domain
        rewrite: (path) => path.replace(/^\/api/, '') // Rewrite the path to make the path a null character
      }
    }
  }
}) 
You can then request data across domains by writing in the file that needs to send the request:
var options = {  // set upaxiosParameters
  url: '/api/login',
  data: {username:username.value,password:password.value},
  method: 'post',
  headers: {'Content-Type':'application/x-www-form-urlencoded'}
}

  axios(options).then((res: any)=>{
      console.log(res);
      if(res.data==='loginOK'){
          router.push('/');
      }else{
          alert('Account password is wrong');
      }
  }) 

The ‘/api’ in the vite.config.js file can be changed to any name you want, and it doesn’t matter if you rewrite it as empty.

Cross-domain processing related to backend SpringBoot

I. Why cross-domain problems occur

Due to browser co-origin policy restrictions. A co-origin policy (Sameoriginpolicy) is a convention, and is a core and a basic security function of the browser. If the co-origin policy is missing, normal functions of the browser may be affected. It can be said that the Web is built on the same source policy, and the browser is only an implementation of the same source policy.

Same Source Policy

The same source policy prevents javascript scripts from one domain from interacting with the contents of another domain. The same source (that is, in the same domain) means that two pages have the same protocol (protocol), host (host), and port number (port).

II. What is Cross-domain

Example:

When any one of the protocol, domain name, and port of a request url is different from the current page url, it is cross-domain.

III. Non-Same Source Restrictions

  • [1] Unable to read cookies, LocalStorage, and IndexedDB for non-homologous pages
  • [2] Cannot touch DOM for non-homologous pages
  • [3] Unable to send AJAX request to non-homologous address

4. How the java backend implements cross-domain requests

For cross-domain requests of CORS, the following modes are available:
  • 1.Return New CorsFilter
  • 2.Rewrite WebMvcConfigurer
  • 3.Using Annotation @CrossOrigin
  • 4.Manually setting the response header(HttpServletResponse)
  • 5.Custom web filter for Cross-Domain
Note
  • The CorFilter/WebMvConfigurer/@CrossOrigin is supported only when the version is higher than SpringMVC 4.2, corresponding to the version of the springBoot 1.3.
  • The first two modes belong to the global CORS configuration, and the last two modes belong to the local CORS configuration. If the local cross-domain rule is used, the global cross-domain rule is overridden. Therefore, fine-grained cross-domain resource control can be performed by using @CrossOrigin annotation.
  • In fact, the ultimate goal of any solution is to modify the response header and add the data required by the browser to the response header, so as to implement cross-domain.
1.Return New CorsFilter(Global Cross-Domain)

In any configuration class, return a new CorsFIlter Bean and add the mapping path and specific CORS configuration path.

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1. Add to CORSConfiguration information
        CorsConfiguration config = new CorsConfiguration();
        //Which origin domains are allowed
        config.addAllowedOrigin("*");
        //Whether to send Cookie
        config.setAllowCredentials(true);
        //Which request methods are allowed?
        config.addAllowedMethod("*");
        //Which original request headers are allowed?
        config.addAllowedHeader("*");
        //What header information is exposed?
        config.addExposedHeader("*");
        //2. Add mapping path
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. return newCorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
} 
2. Rewrite WebMvcConfigurer(Global Cross-Domain)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //Whether to sendCookie
                .allowCredentials(true)
                //Which origin domains are allowed
                .allowedOriginPatterns("*")
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
} 
3.Using annotations(Local Cross Domain)

Use annotation @CrossOrigin: on the controller on class to indicate that all methods of the class allow cross-domain.

@RestController
@CrossOrigin(origins = "*")
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "hello world";
    }
} 
Use annotation @CrossOrigin: on method
@RequestMapping("/hello")
    @CrossOrigin(origins = "*")
     //@CrossOrigin(value = "http://localhost:8081") //Specified concreteipAllow cross domain
    public String hello() {
        return "hello world";
    } 
4. Manually setting the response header(Local Cross Domain)

Use the HttpServletResponse object to add a Access-Control-Allow-Origin to authorize the original domain, where
The value of Origin can also be set to “*,” indicating that all products are released.

@RequestMapping("/index")
public String index(HttpServletResponse response) {
    response.addHeader("Access-Allow-Control-Origin","*");
    return "index";
} 
5. Cross domain with custom filter
First, write a filter with the name MyCorsFilter.java.
package com.xuguoguo.aop;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyCorsFilter 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,content-type");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
} 
Configure this filter in web.xml to take effect
<!-- Cross-domain access START-->
<filter>
 <filter-name>CorsFilter</filter-name>
 <filter-class>com.mesnac.aop.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>CorsFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Cross-domain access END  --> 
Springboot simplifies
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
    @Override
    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-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }
} 
Used in SpringBoot
  • DataGetRequestController
package com.xuguoguo.controller;

import com.xuguoguo.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class DataGetRequestController {

    @GetMapping("/getInt")
    public int getInt(int id){
        return id;
    }

    @GetMapping(value = "/getBox")
    public String getBox(String name,Integer id){
        return "name = " + name + " id = " + id;
    }

    @GetMapping("/getRequestParam")
    public String getRequestParam(@RequestParam(value = "rp",required = false) Integer id){
        return "ID = " + id;
    }

    @GetMapping(value = "/getUser")
    public User getUser(User user){
        return user;
    }

    @GetMapping("/getIds")
    public List<Long> getIds(@RequestParam List<Long> ids){
        return ids;
    }

    @GetMapping(value = "/getMap")
    public Map<String,Object> getMap(@RequestParam Map<String,Object> map){
        return map;
    }

    @GetMapping(value = "/getObj")
    public Object getObj(@RequestParam(name = "ik",required = true,defaultValue = "500") Integer id){
        return id;
    }

    @GetMapping("/getArr")
    public String[] getArr(String[] arr){
        return arr;
    }

    @GetMapping(value = "/getList")
    public List<String> getList(@RequestParam List<String> names){
        return names;
    }

} 
  • DataPostRequestController
package com.xuguoguo.controller;

import com.xuguoguo.entity.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class DataPostRequestController {
    //Receive form
    @PostMapping("/postInt")
    public int postInt(int id){
        return id;
    }

    //Receive form
    @PostMapping("/postBox")
    public String postBox(String name,Integer id){
        return "name = " + name +" id = " + id;
    }

    /**
     * @RequestBody:
     * The request parameters must be inbodyneutral
     *
     * If not added@RequestBody:
     * Requests can be placed inparameter、bodymiddle
     * Complex objects can also be transferred
     * @param user
     * @return
     */
    @PostMapping("/postUser")
    public User postUser(@RequestBody User user){
        return user;
    }

    //Receive form
    @PostMapping("/postUserNoBody")
    public User postUserNoBody( User user){
        return user;
    }

    @PostMapping("/postIds")
    public List<Integer> postIds(@RequestBody List<Integer> ids){
        return ids;
    }

    @PostMapping("/postUsers")
    public List<User> postUsers(@RequestBody List<User> users){
        return users;
    }

    @PostMapping("/postMap")
    public Map<String,Object> postMap(@RequestBody Map<String,Object> map){
        return map;
    }

} 
Axios get Request
<script setup>

import {getData,postData,uploadFile} from './remote.ts'

getData('/getInt',{id:100}).then(function (res) {
  console.log('getInt--->'+res)
})

getData('/getBox',{id:100,name:'Zhang San'}).then(function (res) {
  console.log('getBox--->'+res)
})

getData('/getRequestParam',{rp:100}).then(function (res) {
  console.log('getRequestParam--->'+res)
})

getData('/getUser',{id:100,userName:'Zhang San',password:'123456'}).then(function (res) {
  console.log('getUser--->id:'+res.id+' userName:'+res.userName+' password:'+res.password)
})

getData('/getIds',{ids:'1,2,3,4,5'}).then(function (res) {
  console.log('getIds--->'+res)
  console.log('getIds--->'+res[3])
})

getData('/getMap',{id:100,userName:'Zhang San',password:'123456'}).then(function (res) {
  console.log('getMap--->id:'+res.id+' userName:'+res.userName+' password:'+res.password)
})

getData('/getArr',{arr:'Zhang San,John Doe,Wang Wu'}).then(function (res) {
  console.log('getArr--->'+res)
})

getData('/getList',{names:'Zhang San,John Doe,Wang Wu'}).then(function (res) {
  console.log('getList--->'+res)
})

</script>

<template>

</template> 
Axios post Request
<script setup>

import {getData,postData,postDataForm,uploadFile} from './remote.ts'

postDataForm('/postInt',{id:100}).then(function (res) {
  console.log(res)
  console.log('postInt--->'+res.data)
})

postDataForm('/postBox',{id:100,name:'John Doe'}).then(function (res) {
  console.log(res)
  console.log('postBox--->'+res.data)
})

postData('/postUser',{id:100,userName:'John Doe',password:'123456'}).then(function (res) {
  console.log(res)
  console.log('postUser--->id:'+res.data.id+' userName:'+res.data.userName+' password:'+res.data.password)
})

postDataForm('/postUserNoBody',{id:100,userName:'John Doe',password:'123456'}).then(function (res) {
  console.log(res)
  console.log('postUserNoBody--->id:'+res.data.id+' userName:'+res.data.userName+' password:'+res.data.password)
})

postData('/postIds',[1,2,3,4,5]).then(function (res) {
  console.log(res)
  console.log('postIds--->'+res)
})

postData('/postUsers',[{id:100,userName:'John Doe',password:'123456'},{id:101,userName:'Wang Wu',password:'123456'}]).then(function (res) {
  console.log('----postUsers----')
  console.log(res)
  console.log('----postUsers----')
})

postData('/postMap',{id:100,userName:'John Doe',password:'123456'}).then(function (res) {
  console.log('----postMap----')
  console.log(res)
  console.log('----postMap----')
})
</script>

<template>

</template> 

This document is transferred from https://blog.csdn.net/xu772710255/article/details/135390841,If there is any infringement,Please contact to delete。.