아래 코드에서 AngularJS $http
메소드는 URL을 호출하고 xsrf 객체를 “요청 페이로드”(Chrome 디버거 네트워크 탭에 설명 된대로)로 제출합니다. jQuery $.ajax
메소드는 동일한 호출을 수행하지만 xsrf를 “양식 데이터”로 제출합니다.
AngularJS가 요청 페이로드 대신 xsrf를 양식 데이터로 제출하도록하려면 어떻게해야합니까?
var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};
$http({
method: 'POST',
url: url,
data: xsrf
}).success(function () {});
$.ajax({
type: 'POST',
url: url,
data: xsrf,
dataType: 'json',
success: function() {}
});
답변
전달 된 $ http 객체에 다음 줄을 추가해야합니다.
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
그리고 전달 된 데이터는 URL 인코딩 문자열로 변환되어야합니다.
> $.param({fkey: "key"})
'fkey=key'
따라서 다음과 같은 것이 있습니다.
$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
보낸 사람 : https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ
최신 정보
AngularJS V1.4에 추가 된 새로운 서비스를 사용하려면
답변
솔루션에서 jQuery를 사용하지 않으려면 시도해보십시오. 해결책은 여기에서 https : //.com/a/1714899/1784301
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: xsrf
}).success(function () {});
답변
이 문제를 둘러싼 혼란은 계속해서 블로그 게시물을 작성하도록 영감을주었습니다. 이 게시물에서 제안하는 솔루션은 $ http 서비스 호출을 위해 데이터 객체를 매개 변수화하는 것을 제한하지 않기 때문에 현재 최고 등급 솔루션보다 낫습니다. 즉 내 솔루션을 사용하면 실제 데이터 객체를 계속 $ http.post () 등에 전달하고 원하는 결과를 얻을 수 있습니다.
또한 최고 등급의 답변은 $ .param () 함수의 페이지에 전체 jQuery를 포함시키는 것에 의존하지만 내 솔루션은 jQuery에 독립적이며 순수한 AngularJS가 준비되어 있습니다.
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
도움이 되었기를 바랍니다.
답변
나는 다른 답변을 몇 가지 가지고 조금 더 깨끗하게 만들었습니다 .config()
.app.js의 angular.module 끝에이 호출을 넣으 십시오.
.config(['$httpProvider', function ($httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
var key, result = [];
if (typeof data === "string")
return data;
for (key in data) {
if (data.hasOwnProperty(key))
result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
}
return result.join("&");
});
}]);
답변
AngularJS v1.4.0부터는 문서 페이지$httpParamSerializer
에 나열된 규칙에 따라 객체를 HTTP 요청의 일부로 변환 하는 기본 제공 서비스가 있습니다 .
다음과 같이 사용할 수 있습니다 :
$http.post('http://example.com', $httpParamSerializer(formDataObj)).
success(function(data){/* response status 200-299 */}).
error(function(data){/* response status 400-999 */});
올바른 양식 게시물의 경우 Content-Type
헤더를 변경해야합니다. 모든 POST 요청에 대해 전체적으로이 작업을 수행하기 위해이 코드 (Albireo의 반 답변에서 가져온)를 사용할 수 있습니다.
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
현재 게시물에 대해서만이 작업을 수행하려면 headers
request-object 의 속성을 수정해야합니다.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializer(formDataObj)
};
$http(req);
답변
전역 적으로 동작을 정의 할 수 있습니다.
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
따라서 매번 재정의하지 않아도됩니다.
$http.post("/handle/post", {
foo: "FOO",
bar: "BAR"
}).success(function (data, status, headers, config) {
// TODO
}).error(function (data, status, headers, config) {
// TODO
});
답변
임시 해결책으로 POST를 수신하는 코드가 애플리케이션 / json 데이터에 응답하도록 만들 수 있습니다. PHP의 경우 아래 코드를 추가하여 양식 인코딩 또는 JSON으로 POST 할 수 있습니다.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
