方法POST在向REST服务发送请求时不起作用

Method POST not working when send request to REST Service

本文关键字:请求 不起作用 服务 POST 在向 REST 方法      更新时间:2023-09-26

我的问题如下:当我向REST服务发送POST请求时,我得到了Access Control Allow Origin错误,但请求get它正在工作。

这是我的休息服务:

@Path("/createUser")
@RequestScoped
public class ClientRestService {
@Inject
private ClientManager clientManager;
@POST
@Path("{name}/{surname}/{adress}")
@Produces(MediaType.APPLICATION_JSON)
public Response createUser(@PathParam("name")String name,  @PathParam("surname")String surname, @PathParam("adress")String adress) {
    Client client = new Client(name,surname,adress);

    Response.ResponseBuilder builder = Response.ok("POST It's working.!!!");
    builder.header("Access-Control-Allow-Origin", "*");
    builder.header("Access-Control-Allow-Methods", "POST");
    return builder.build();
}
@GET
public Response getMetod() {
    Response.ResponseBuilder builder = Response.ok("GET It's working.");
    builder.header("Access-Control-Allow-Origin", "*");
    return builder.build();
}
}

这是客户:

$(document).ready(function() {
$.ajax({
    url: 'http://localhost:8080/Bank_Project_Test/MyApp/createUser',
    type: 'POST',
    data: 'name=SomeName'+
        '&surname=SomeSurname'+
        '&adress=SomeAdress', 
    success: function(success) {
        alert(success); 
    }
});
});

可能会因为cors飞行前请求而失败?

如果在失败时在浏览器中看到OPTIONS-方法请求,那么您也需要在服务器实现中处理这些请求。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests