我尝试通过服务将数据传递到控制器,然后再传递到存储库,从而将数据发布到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);
}
}
1条答案
按热度按时间yquaqz181#
所以我不确定这是否是最优的解决方案,但这是一个解决方案。
我添加了这段代码,基本上告诉CORS-Config直接允许CrossOrigin,它似乎已经工作: