POST GWT CORS请求有效,但PUT CORS请求不

时间:2017-09-13 16:16:41

标签: http gwt cors

我正在为个人项目编写GWT前端,我遇到了一些HTTP请求的问题。当我执行CORS POST请求时,它可以正常工作

String url = BASE_URL + "students/";

RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);

try {
    builder.sendRequest(studentWriter.write(student), new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            addItemDialog.close();
            responseDialog.open();
            loadingIcon.setVisible(false);
            responseHeading.setText("No response");
            responseLabel.setText(request.toString());
        }

        public void onResponseReceived(Request request, Response response) {
            loadingIcon.setVisible(false);
            String responseText = response.getText();

            List<Map.Entry<Integer, Student>> students = model.getList();
            Integer studentId = Integer.parseInt(responseText);

            students.add(new AbstractMap.SimpleEntry<>(studentId, student));
            model.setList(students);

            // clear text fields
            className.setValue("");
            additionLevel.setValue("");
            additionProblems.setValue("");
            subtractionLevel.setValue("");
            subtractionProblems.setValue("");
            multiplicationLevel.setValue("");
            multiplicationProblems.setValue("");
            divisionLevel.setValue("");
            divisionProblems.setValue("");

            addItemDialog.close();
        }
    });

} catch (RequestException _) {
    // Code omitted for clarity
}

选项请求得到200响应(下面的chrome网络检查):

General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:OPTIONS
Status Code:200 
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade

Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:post, get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:56:32 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:8nJ2gzqHFPiiDOOeEelzkpI7Ga9SFdEcljiLt2pvm7Z995_GicxPVw==
x-amzn-requestid:bb0e23db-9893-11e7-bbbe-9bea7d9d70bf
x-amzn-trace-id:sampled=0;root=1-59b94720-d892209d8c5c2a04832bdb85
x-cache:Miss from cloudfront

Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:POST
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

然后按预期发生POST请求

General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:POST
Status Code:201 
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade

Response Headers
access-control-allow-origin:*
content-length:1
content-type:application/json
date:Wed, 13 Sep 2017 14:56:33 GMT
status:201
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:gxYrwctM75ObiPyS4nD69jXSO4dBaMAOZmXXX0mPE4wMgCdcjUSQsA==
x-amzn-requestid:bb381a33-9893-11e7-a1f1-17fd67ca388c
x-amzn-trace-id:sampled=0;root=1-59b94720-1c1e3a8d8c9ce2741c789241
x-cache:Miss from cloudfront

Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:POST
:path:/v1/students/
:scheme:https
accept:application/json
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
content-length:224
content-type:application/vnd.onelostlogician.student+json
lambda-authorization:Basic [redacted]
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

Request Payload
{"className":"6T","additionProblemId":4,"additionNoOfProblems":5,"subtractionProblemId":3,"subtractionNoOfProblems":5,"multiplicationProblemId":2,"multiplicationNoOfProblems":5,"divisionProblemId":1,"divisionNoOfProblems":5}

不幸的是,在同一台服务器上对非常相似的资源的PUT请求却没有。代码几乎相同:

String url = BASE_URL + "students/" + studentId;

RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);

try {
    builder.sendRequest(studentWriter.write(student), new RequestCallback() {
        public void onError(Request request, Throwable exception) {
            addItemDialog.close();
            responseDialog.open();
            loadingIcon.setVisible(false);
            responseHeading.setText("No response");
            responseLabel.setText(request.toString());
        }

        public void onResponseReceived(Request request, Response response) {
            loadingIcon.setVisible(false);
            responseDialog.open();
            loadingIcon.setVisible(false);
            responseHeading.setText("Response: " + response.getStatusCode());
            responseLabel.setText(response.getText());
        }
    });

} catch (RequestException _) {
    // Code omitted for clarity
}

选项请求获得200响应:

General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/4
Request Method:OPTIONS
Status Code:200 
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade

Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:58:38 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:0PoyOa6oDBSmU7iCWZyeSZFqWxZvumN8C4GtHn8rsoJK5AURbj3kxQ==
x-amzn-requestid:063270d4-9894-11e7-9d66-71b07b2689ef
x-amzn-trace-id:sampled=0;root=1-59b9479e-39be94b25784b92027fa2753
x-cache:Miss from cloudfront

Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/4
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:PUT
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

...但在收到成功的OPTIONS回复后,它根本没有提出PUT请求。

在Chrome控制台中,我得到:

  

XMLHTTPRequest无法加载https://[redacted]/v1/students/5。方法   预检中的Access-Control-Allow-Methods不允许PUT   响应

我不明白这个错误,因为我们可以在上面显示的预检put请求的access-control-allow-methods响应标题中看到“OPTIONS”。

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:0)

在POST响应中,允许的方法标题是

this.validationService...

在PUT响应中,允许的方法标题是

access-control-allow-methods:post, get, put

请注意,所需方法是POST案例列表中的第一个,但在PUT案例的列表中排在第二位。当我修改服务器以首先在列表中考虑该方法时(并且,为了使其区分大小写,因为HTTP方法名称区分大小写),然后浏览器执行所需的后续PUT请求。