Solve the cross-domain problem in Spring Boot's front-end and back-end separation development mode

In actual development, we often encounter the problem of cross-domain access between the front-end Vue application and the back-end Spring Boot API interface. This blog will share the practical experience of solving the cross-domain problem of Spring Boot front-end Vue, and help developers quickly solve this problem.

1. The cause of the cross-domain problem

Cross-origin issues are caused by the browser's same-origin policy. The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. When the protocol, host name or port number is different, the browser will think that this is a cross-domain access and reject the request.

Two, the solution

1. Backend configuration

In the Spring Boot backend project, we can allow cross-domain requests for front-end Vue applications by adding cross-domain configuration.

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

In the above code, @Configurationannotations are used to mark a configuration class and implement WebMvcConfigurerthe interface. In addCorsMappingsthe method, it is configured to allow all sources ( allowedOrigins("*")), all HTTP methods ( allowedMethods("*")), all request headers ( allowedHeaders("*")), support cross-domain carrying of cookies ( allowCredentials(true)), and cache time ( maxAge(3600)).

2. Front-end configuration

In the Vue front-end project, we can vue.config.jssolve cross-domain problems through configuration files.

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target 'http://localhost:8080',  // 后端API接口地址
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}

In the above code, we configure the agent through the properties devServerof the configuration item . proxyProxy the request starting with in the request path apito the specified backend API interface address (here is http://localhost:8080). changeOriginSet to truemeans enable cross-domain.

3. Practical examples

In actual development, we can use the following examples to demonstrate practical experience in solving Vue cross-domain problems on the Spring Boot side.

Example backend code:

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}
```javascript
axios.get('/api/hello')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error(error);
    });

In the above example, the backend provides a simple interface /api/hello, and the frontend axiosobtains data by sending GET requests.

Four. Summary

This blog introduces the practical experience of solving the cross-domain problem of Spring Boot front-end Vue, and provides configuration examples of back-end and front-end. By configuring the back-end and front-end, we can easily solve cross-domain problems and achieve normal front-end and back-end interactions. I hope this article can be helpful to developers, and everyone is welcome to spread and share!

The above content is for reference only, and the specific situation needs to be adjusted according to the actual project. If there is a better solution, please leave a message to discuss.

References

Guess you like

Origin blog.csdn.net/weixin_39709134/article/details/132495273