我在localhost:8080上有一个vertx后端服务器,正在回答REST请求。
发送GET请求时,一切正常。
但是在带有参数的DELETE请求中,我收到CORS错误...
我的后端服务器如下:
@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();
}
}
我希望.putHeader(“ Access-Control-Allow-Origin”,“ *”)部分可以解决所有CORS问题,但是以某种方式仅适用于代码的GET部分...
我的前端是一个运行在localhost:4200上的Angular5应用程序,如下所示:
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);
}
}
答案 0 :(得分:0)
Vert.x提供了一个开箱即用的CORS处理程序:
Router router = Router.router(vertx);
router.route().handler(CorsHandler.create("*"));
答案 1 :(得分:0)