I want to a send POST request from my angular app to my server (written with spring-boot). The request gets denied with the message "cors header ‘access-control-allow-origin’ missing".
I enabled the origin of my angular app "http://localhost:4200" like I did for my other RestControllers (Which work). The only difference as far as I can tell is that I handel POST requests in my not working controller.
Controller
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {
@Autowired
private ReqRepository reqRepository;
@PostMapping("/reqs")
public Req saveReq (@Valid @RequestBody Req req) {
return reqRepository.save(req);
}
}
Repository
@Repository
public interface ReqRepository extends JpaRepository<Req, Long> {
}
Angular Service
@Injectable()
export class ReqService {
private httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
};
constructor(private http: HttpClient) {}
sendReq(req: Req): Observable<Req> {
return this.http.post<Req>('http://localhost:8080/reqs', req, this.httpOptions);
}
}
I thought allowing the origin would be enough so the request is possible but it get's blocked. It seems like I am missing something to enable POST requests.
Update
I further tested the controller and it works for GET requests. I just change the the method, so it seems like the problem lies in the POST request. Below ist the controller with a GET test endpoint instead of a POST endpoint
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class Controller {
@Autowired
private ReqRepository reqRepository;
@GetMapping("/reqs")
public Page<Req> testCall (Pageable pageable) {
System.out.println("Geeting request");
return reqRepository.findAll(pageable);
}
}