Tag Archives: AccessControlAllowOrigin

[Solved] interceptor Cross-Domain Access-Control-Allow-Origin Error

I use vue3 + spring boot, which is developed by front-end and back-end separation technology. For cross-domain problems, I add the following code:

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)
                .maxAge(3600); // No further pre-testing required within 1 hour (send OPTIONS request)
    }

}

The above code is useless, and then it is used in the interceptor to add the following code:

String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", origin);

Add to solve the problem.

Vue + Django Project-Browser cross-domain error: Access-Control-Allow-Origin

Browser error reporting

Check the front end and check the error information as follows

Access to XMLHttpRequest at ‘ http://127.0.0.1:8000/categorys/ ‘ from origin ‘ http://localhost:8080 ‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Solve cross domain problems through the back end

Refer to the solution on GitHub

Search Django CORS headers to see

1. Installing in a virtual environment

python -m pip install django-cors-headers

2. Configure settings

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]


MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]
# CorsMiddleware should be prior to CommonMiddleware

CORS_ALLOW_ALL_ORIGINS=True

After restarting the project, the browser will no longer report cross-domain errors