mariadb 即使Controller已启用交叉源并设置了标题,对XMLHttpRequest的访问仍被CORS策略阻止

wlp8pajw  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(106)

我尝试通过服务将数据传递到控制器,然后再传递到存储库,从而将数据发布到MariaDB。然而,当尝试对控制器URL执行http.post时,我得到了响应:Access to XMLHttpRequest at 'http://localhost:8080/api/car/create' from origin 'http://localhost:4200' 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.虽然我发现这个错误已经被描述了很多次,但建议的解决方案似乎还没有为我工作,因为我既启用了http-header中的所有内容,也启用了我的控制器中的@Crossorigin
下面是我的代码的重要部分:
服务

readonly httpOptions = {
    headers: new HttpHeaders({
      "ACCESS_CONTROL_ALLOW_ORIGIN": "http://localhost:4200",
      "ACCESS_CONTROL_ALLOW_CREDENTIALS": "true"
    })
  };

  public save(car: Car) {
    return this.http.post('http://localhost:8080/api/car/create', car, this.httpOptions);
  }

主计长

@Controller
@RequestMapping("/api/car")
@CrossOrigin(origins = "http://localhost:4200")
@Transactional
public class CarController {

    @Autowired
    public CarController(CarRepository carRepository) {

        this.carRepository = carRepository;
    }

    @PostMapping(value = "/create")
    @ResponseBody
    @Transactional
    public void addCars(@RequestBody final car car) {
        this.carRepository.save(car);
    }
}
yquaqz18

yquaqz181#

所以我不确定这是否是最优的解决方案,但这是一个解决方案。
我添加了这段代码,基本上告诉CORS-Config直接允许CrossOrigin,它似乎已经工作:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println("CORS Config success");
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200"); // "/create-cars"
            }
        };

    }

相关问题