current position:Home>This paper solves the cross domain problem Vue + springboot caused by the separation of front and back ends

This paper solves the cross domain problem Vue + springboot caused by the separation of front and back ends

2022-04-29 04:26:25hellcvr

problem :axios Cross domain and every access caused by accessing back-end data session Dissimilarity

The front end

my vue Project creation command :

vue init webpack project_name

vue Project creation suggestions are consistent with mine , Only in this way can the project directory file be consistent .

index.js The document is as shown in the figure :

 Please add a picture description

Add the following :

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      'api': {
        target: 'http://localhost:8088', //  Here is the back-end address 
        changeOrigin: true, //  Allow cross-domain 
        pathRewrite: {
          '^/api': '' //  The prefix added every time the backend accesses , Like your request /login => /api/login
        }			 //  No prefix requirement, delete api that will do 

After configuration, see the figure :
 Please add a picture description

main.js Add below :

import qs from 'qs'
import store from './store'

axios.defaults.baseURL = 'http://localhost:8088/api' //  Note that this is the same as the above target
//  Bring credential information to the request , Here's the solution session The problem of inconsistency 
axios.defaults.withCredentials = true
Vue.prototype.$axios = axios

So far, the front end determines the cross domain and session The problem of inconsistency .

Back end part

Create a config package , establish

Add the following code :

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class MyWebMvcConfig implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry registry) {
        // All requests are allowed to cross domain 
            	/**  Here is the front-end domain name + port ,  If all access is allowed, change to * */
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // Allow all methods 

So far, the cross domain problem of the back end is solved .

We all know that there is a note @CrossOrigin Annotations can solve cross domain problems , But this annotation is currently only in Get Work methodically ,post It's useless , So use the above method to solve the cross domain problem .

Special issues

vue Often with element-ui and axios Use ,axios The data will be put into the request body by default when requesting , In this way, the back-end can only accept data through annotation @RequestBody, More trouble , It cannot be obtained directly in the form of method parameters like transferring form data , This question is mainly aimed at POST request .

stay main.js Add the following code to solve the above problem :

import qs from 'qs'

axios.interceptors.request.use((config) => {
  if (config.method === 'post' && !config.url.includes('upload')) { = qs.stringify(
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  return config
}, (error) => {
  return Promise.reject(error)

The function of the above code axios The interceptor modifies the request header , Simple code , But you can see that the above judge at the same time url Does it contain upload request , This is because I use element-ui Self contained components upload There was a problem with the component bug, On the contrary, the back-end formal parameter cannot accept data , So here we judge if it includes upload Use the default parameter transfer method .

Corresponding upload The code is as follows :

    <el-upload :with-credentials="true" :http-request="upload" action="" multiple :limit="1" :on-exceed="handleExceed" :before-remove="beforeRemove" ref="upload" :file-list="fileList">
    <el-button type="primary"> Click upload </el-button>

<script> export default {
       props: ['parentId'], data () {
       return {
       fileList: [] } }, methods: {
       handleExceed (files, fileList) {
       this.$message.warning(` Current restrictions on choice  1  File , This time I chose  ${
        files.length}  File , A total of  ${
        files.length + fileList.length}  File `) }, beforeRemove (file, fileList) {
       return this.$confirm(` Confirm removal  ${}`) }, upload (param) {
       const formData = new FormData() formData.append('file', param.file) formData.append('id', this.parentId) //  Here you can add verification data  const url = '/admin/upload' this.$, formData ).then(resp => {
       this.$refs.upload.clearFiles() this.$emit('onUpload') }).catch(resp => {
       console.log(' Upload failed ') }) } } } </script>

copyright notice
author[hellcvr],Please bring the original link to reprint, thank you.

Random recommended