2016-09-14 5 views
1

次のコードでは、パラメータuserIdを使用してJQueryからJAX-RSサーバでメソッド「保存」をリクエストしています。このJQueryはGoogle Chrome拡張機能から実行されます(localhostからテストした場合と同じ問題)。JQueryからJava(JAX-RS)サーバへのPOSTリクエストでパラメータが受信されない

<script> 
    $.post('https://example.com:8082/save', { userId: 'myuser' }) 
    .done(function(data) { 
    console.log(data); 
    }); 
</script> 

(Chromeの拡張機能の内部)

のindex.htmlは、要求を受信し、私はいつも(下記参照)エラーメッセージERROR: user not specifiedを取得しています。

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 

クロームデバッグ

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 

EDIT:はそれはそれは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> 
+0

あなたのブラウザの開発ツールを見てください。体はどのように見えますか? –

+1

[JAX-RSとjquery.ajax()を使用したパラメータの取得]の複製の可能性があります。(http://stackoverflow.com/questions/13275318/retrieving-parameters-using-jax-rs-and-jquery-ajax) –

+0

@AlexeySoshinあなたのリンクに指定された "@Consumes"を追加しましたが、同じエラーが発生します。私はさらに詳しい情報で私の質問を更新しました – Arturo

答えて

1

私はそれが代わりにXMLHttpRequestを働かせました。おそらくcontent-typeヘッダーを挿入すると違いが生じたでしょうか?これは作業コードです:

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); 
+0

jQueryはデフォルトで「application/x-www-form-urlencoded; charset = UTF-8」とされています – Xan

関連する問題