Я новичок в весенней загрузке и сталкиваюсь с ошибкой CORS в пружине. Я делюсь своим кодом.
Демо-приложение. java
package com.example.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication(scanBasePackages={"com.example.mapper","com.example.services"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/demo")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH")
.allowCredentials(true);
}
};
}
}
ServiceController. java
package com.example.controller;
import com.example.response.Response;
import com.example.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import com.example.model.User;
@RestController
@RequestMapping(value="/demo")
public class ServiceController {
@Autowired
private UserServices userServices;
public UserServices getUserServices() {
return userServices;
}
public void setUserServices(UserServices userServices) {
this.userServices = userServices;
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Response login(@RequestBody User user) throws Exception {
HttpHeaders headers = new HttpHeaders();
Response response = new Response();
response.setMessage("Login Successfull");
response.setCode(200);
return response;
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/sign-up", method = RequestMethod.POST)
public Response signUp(@RequestBody User user) throws Exception {
System.out.print("**************Sign up *****************");
Response response = new Response();
if(userServices.signupService(user)==1) {
response.setCode(200);
response.setMessage("data saved");
}
else{
response.setMessage("unable to save data");
response.setCode(500);
}
return response;
}
}
Я добавил web mvc configurer и аннотацию @CrossOrigin, по-прежнему получаю ту же ошибку, я использую реагирующий на родной язык в веб-интерфейсе. Что не так с моим кодом, Должен ли я отправить заголовок в ответ, пожалуйста, дайте мне знать .. спасибо