在下面的代码中,我使用参数 userId 从 JQuery 向 JAX-RS 服务器上的方法“save”发出请求。此 JQuery 从 Google Chrome 扩展程序运行(从本地主机测试时出现同样的问题)。
index.html(Chrome 扩展程序内)
<script>
$.post('https://example.com:8082/save', { userId: 'myuser' } )
.done(function( data ) {
console.log(data);
});
</script>
已收到请求,但我总是收到错误消息错误:未指定用户
(见下文)。
JAX-RS 服务器端
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/save")
public Response save(@FormParam("userId") String userId) {
if(userId == null) {
return Response.ok("ERROR: user not specified", MediaType.APPLICATION_JSON).build();
}
else {
[...]
}
}
我已经测试了来自 CURL 的相同请求,效果很好。
curl --data "userId=myuser" https://example.com:8082/save
Chrome 调试
Request URL:https://example.com:8082/save
Request Method:POST
Status Code:200 OK
Remote Address:131.224.32.213:8082
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://myteam.slack.com
Access-Control-Allow-Credentials: true
Content-Type: application/json
Content-Length: 25
Date: Wed, 14 Sep 2016 17:33:05 GMT
Connection: close
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en,es;q=0.8
Connection:keep-alive
Content-Length:16
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:example.com:8082
Origin:https://myteam.slack.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
userId=myuser
编辑:这是否可能是由 CORS 规则引起的?我正常收到 POST 请求,但没有参数。这些是我在 Tomcat 上的过滤器。我需要 JAX-RS 上的任何 CORS 语句吗?
Tomcat8 conf/web.xml
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
最佳答案
我让它使用 XMLHttpRequest 来代替。也许插入内容类型 header 会产生影响?这是工作代码:
var http = new XMLHttpRequest();
var url = "https://example.com:8082/save";
var params = "userId=myuser";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
关于javascript - 从 JQuery 到 Java (JAX-RS) 服务器的 POST 请求中从未收到参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496186/