preface

Recently Chinese New Year at home boring, just I have plenty of time to study the Vue, by the way, do check the add or delete one small change + keyword matching + paging dome, but using the Vue request back-end provide Api is found a big problem, before and after the end of the separation, but when the request is bound to have a cross-domain this kind of problem, and how to solve?

Front-end solutions

Since most of the Vue projects are scaffolded quickly, we can create a vue.config.js configuration file directly in the project, and then configure the proxy in it to solve the problem

module.exports = {
    devServer: {
        proxy: {
            '/api': {target: 'http://127.0.0.1:8181'.// Address of the API server
                ws: true./ / agency web sockets
                changeOrigin: true.// Whether to cross domains, virtual sites need to manage origin
                pathRewrite: {
                    '^/api': ' '}}}}};Copy the code

After this configuration, when Vue uses AXIOS or Ajax to call the background API, it only needs to send the request in the request path format of/API /xx/xx. This method has two advantages: 1. It solves the cross-domain problem, and only needs to write the interface called each time the request. The prefix does not need to be written again. 2: Since the proxy is provided, it is convenient to hide the real Api server address and ensure the security of the server

Back-end solutions

Ideas: We can create a config package in the SpringBoot project, in which we can create a WebConfig class. Solve cross-domain problems by implementing the addCorsMappings method of the WebMvcConfigurer interface

package com.vue.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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

This approach can also be resolved, but it is better to provide cross-domain solutions consistently on both the front and back ends