Access to XMLHttpRequest at 'http://localhost:8080/register' from origin 'http://localhost:63342' has been blocked by CORS policy:

Spring mvc

Полный трейс:

Access to XMLHttpRequest at 'http://localhost:8080/register' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Пытаюсь зарегать пользователя с помощью ajax:

const serverAddress = "http://localhost:8080";
const registerAddress = "/register";

$("#registration").submit(function () {
   let registerUserDto = {
      "firstName":$("#firstName"),
      "lastName":$("#lastName"),
      "username":$("#registerUsername"),
      "password":$("#registerPassword"),
      "repeatPassword":$("#repeatPassword")
   };
    $.ajax({
        url: serverAddress + registerAddress,
        method: 'POST',
        data: JSON.stringify(registerUserDto),
        contentType: "application/json; charset=utf-8",
        statusCode: {
            400: function () {
                $("#badCredentials").text("Bad credentials");
            },
            201: function () {
                alert("Nice!");
                window.location = 'login.html';
            }
        }
    });
});

Нагуглила ошибку, пишут что нужно вебсконфигурировать, что я и сделала:

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

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*");
    }
}

По идее, теперь любой сайт может попросить пообщаться с сервером, но не работает(((


Ответы (0 шт):