2016-08-18 4 views
2

REST API에 게시하려는 jQuery를 실행하는 아주 간단한 HTML 페이지가 있습니다. 여기 내 코드가있다.jQuery.AJAX는 POST 대신 GET을 사용합니다.

<script type="text/javascript" language="javascript"> 
    var user = 'someuser'; 
    var pass = 'somepassword'; 
    var payload = { 
     "value1": "first value", 
     "value2": "second value" 
    }; 
    var rootUrl = 'http://someinternalserver:8888/api/Method'; 
</script> 
<script language="javascript" type="text/javascript" id="postWtnBlock"> 
    function postValue_Go() { 
     $.ajax({ 
      url: rootUrl, 
      // Removing the next line or changing the value to 'JSON' results in an OPTIONS request. 
      dataType: 'JSONP', 
      data: JSON.stringify(payload), 
      method: 'POST', 
      user: user, 
      password: pass, 
      beforeSend: function (req) { 
       req.setRequestHeader('Authorization', 'BASIC ' + btoa(user + ':' + pass)); 
      }, 
      success: function (data) { 
       alert(data); 
      }, 
      error: function (xhr) { 
       alert(xhr.status + ' ' + xhr.statusText); 
      } 
     }); 
    } 
</script> 

두 가지 일이 여기 일어나고 있습니다.

1) 모든 요청이 POST가 아닌 GET 요청으로 전송됩니다. 2) 권한 부여 헤더는 요청에 절대 적용되지 않습니다. 그것은 항상 빠져 있습니다.

왜 이런지 모르겠습니다.

# 1 업데이트 :

POST http://someinternalserver:8888/api/Method/ HTTP/1.1 
Host: someinternalserver:8888 
Connection: keep-alive 
Content-Length: 693 
Accept: */* 
Origin: http://devserver 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 
Referer: http://devserver/samples/ExternalAPI/ 
Accept-Encoding: gzip, deflate 
Accept-Language: en-US,en;q=0.8 
Cookie: someCookieValue=Boo; someOtherCookieValue=Yum; 

{"value1": "first value","value2": "second value"} 

그리고 원시 응답 : 새로운 postValue_Go()는 다음과 같습니다 ...

function postValue_Go() { 
     $.ajax({ 
      url: rootUrl, 
      data: JSON.stringify(payload), 
      method: 'POST', 
      username: user, 
      password: pass, 
      xhrFields: { 
       withCredentials: true 
      }, 
      success: function (data) { 
       alert(data); 
      }, 
      error: function (xhr) { 
       alert(xhr.status + ' ' + xhr.statusText); 
      } 
     }); 
    } 

다음은 원시 피들러에서 캡처 요청,의

, 그 역시 Fiddler에서 잡혔습니다.

HTTP/1.1 401 Unauthorized 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/7.5 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Fri, 19 Aug 2016 17:12:29 GMT 
Content-Length: 61 

{"Message":"Authorization has been denied for this request."} 
+0

이 api return jsonp입니까? 왜 [http://stackoverflow.com/questions/7613815/callback-function-for-jsonp-with-jquery-ajax](jsonp 콜백)]을 추가하지 않았습니까? network-> xhr 화면을 공유 할 수 있습니까? –

+0

데이터 타입을'JSONP'에서'JSON'으로 바꾸면 질문은 OPTIONS 요청이됩니다. – amber

+1

JSONP는 GET 요청이므로 JSONP가 작동하는 방식입니다. – epascarello

답변

0

JSONP는 src 속성은 모든이에 번들로 요청 된 데이터와 스크립트를 반환 (GET 요청을 수행) 웹 서비스를 가리키는 웹 페이지에 스크립트를 추가하기 때문에 그것은 GET 요청으로 전송되는 것 콜백 함수.

iframe 등 (참조)으로 심각한 다리 작업을하고 싶다면 JSONP를 통해 POST 요청을 수행 할 수 있지만 대부분의 경우 의도적으로 GET 요청으로 제한됩니다.

현재 페이지에 추가 할 스크립트에 대해 보낸 헤더를 수정할 방법이 없으므로 권한 부여 헤더가 설정되지 않습니다.

+0

'JSONP'을 제거하면 생성 된 요청은'OPTIONS' 요청이됩니다. – amber

+1

@amber 나는 그것이 맞춤 헤더를 설정하고 있기 때문이라고 생각합니다. [여기] (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests) – stevenelberger

+0

뭔가를했습니다. 'beforeSend' 핸들러를 주석 처리했는데, 실제로'POST'가 있지만 서버는 401 Not Authorized로 돌아 왔습니다. 원시 요청을 보면'user' 및'password' 설정 값으로 설정된 권한 정보가 표시되지 않습니다. – amber

관련 문제