Reputation: 367
I have a vertx backend server on localhost:8080 answering REST request.
When sending a GET request, everything works fine.
But on a DELETE request with params I get CORS errors...
My backend server looks like this:
@Override
public void start(Future<Void> fut) {
Router router = Router.router(vertx);
router.route("/").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/html").end("<h1>Hello from my first Vert.x 3 application</h1>");
});
router.get("/api/whiskies").handler(this::getAll);
router.delete("/api/whiskies/:id").handler(this::deleteOne);
vertx.createHttpServer().requestHandler(router::accept).listen(
config().getInteger("http.port", 8080), result -> {
if (result.succeeded()) {
fut.complete();
} else {
fut.fail(result.cause());
}
});
}
private void getAll(RoutingContext routingContext) {
routingContext.response().putHeader("content-type", "application/json; charset=utf-8")
.putHeader("Access-Control-Allow-Origin", "*")
.end(Json.encodePrettily(products.values()));
}
private void deleteOne(RoutingContext routingContext) {
Integer idAsInteger = Integer.valueOf(routingContext.request().getParam("id"));
products.remove(idAsInteger);
routingContext.response().putHeader("Access-Control-Allow-Origin", "*")
.setStatusCode(204).end();
}
}
I hoped, that the .putHeader("Access-Control-Allow-Origin", "*") part would fix all CORS problems, but somehow that only works for the GET part of the code...
My front end is an Angular5 application running on localhost:4200 looking like this:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class HttpService {
constructor(private http:HttpClient) {}
getWhiskies() {
return this.http.get('http://localhost:8080/api/whiskies');
}
deleteWhisky(id :number) {
return this.http.delete('http://localhost:8080/api/whiskies/' + id);
}
}
Upvotes: 0
Views: 2176
Reputation: 367
Ok, so I was able to fix it by defining allowed methods as well as the "Content-Type" header.
See the following link for references:
Upvotes: 2
Reputation: 17721
Vert.x provides you with a CORS handler out of the box:
Router router = Router.router(vertx);
router.route().handler(CorsHandler.create("*"));
Upvotes: 1