AngularJS-$ http.post가 JSON 대신 요청 매개 변수를 보내는 방법은 무엇입니까?
jQuery의 post 메소드를 통해 AJAX POST 요청을하는 오래된 코드가 있으며 다음과 같습니다.
$.post("/foo/bar", requestData,
function(responseData)
{
//do stuff with response
}
requestData
기본 문자열 속성이있는 자바 스크립트 객체 일뿐입니다.
Angular를 사용하기 위해 물건을 옮기는 중이며이 호출을 $ http.post로 바꾸고 싶습니다. 나는 다음을 생각해 냈다.
$http.post("/foo/bar", requestData).success(
function(responseData) {
//do stuff with response
}
});
이 작업을 수행했을 때 서버에서 500 오류 응답을 받았습니다. Firebug를 사용하여 다음과 같이 요청 본문을 보냈습니다.
{"param1":"value1","param2":"value2","param3":"value3"}
성공적인 jQuery $.post
는 다음과 같이 본문을 보냅니다.
param1=value1¶m2=value2¶m3=value3
내가 맞고있는 엔드 포인트는 JSON이 아닌 요청 매개 변수를 기다리고 있습니다. 그래서 제 질문은 $http.post
자바 스크립트 객체를 JSON 대신 요청 매개 변수로 보내 라고 말할 수 있습니까? 예, 객체에서 직접 문자열을 생성 할 수 있다는 것을 알고 있지만 Angular가 즉시 이것을 제공하는지 알고 싶습니다.
내가 생각하는 params
구성 매개 변수는 대신 몸의 URL에 문자열을 추가하기 때문에 여기에 작동하지 않습니다하지만 (의 jQuery 사용하여 변환 기본의 글로벌 재정의 예입니다 무엇 Infeligo 여기 제안에 추가 PARAM을 변환하는 예로서 param 문자열에 대한 데이터).
전역 transformRequest 함수를 설정하십시오.
var app = angular.module('myApp');
app.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return $.param(data);
}
});
이렇게하면 $ http.post에 대한 모든 호출이 자동으로 본문을 jQuery $.post
호출에서 사용하는 것과 동일한 매개 변수 형식으로 변환합니다 .
호출 당 또는 다음과 같이 전역 적으로 Content-Type 헤더를 설정할 수도 있습니다.
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
호출 당 샘플 비 글로벌 transformRequest :
var transform = function(data){
return $.param(data);
}
$http.post("/foo/bar", requestData, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
}).success(function(responseData) {
//do stuff with response
});
Angular> = 1.4를 사용하는 경우 사용자 정의 또는 외부에 의존하지 않는 가장 깨끗한 솔루션이 있습니다.
angular.module('yourModule')
.config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
그런 다음 앱 어디에서나이 작업을 수행 할 수 있습니다.
$http({
method: 'POST',
url: '/requesturl',
data: {
param1: 'value1',
param2: 'value2'
}
});
그리고 엔드 포인트의 POST 요청에서 일반적으로 예상되는대로 데이터를 올바르게 직렬화하여 Content-Type 헤더 와 함께 param1=value1¶m2=value2
전송 합니다./requesturl
application/x-www-form-urlencoded; charset=utf-8
AngularJS 문서에서 :
params – {Object.} – URL 다음에? key1 = value1 & key2 = value2로 바뀔 문자열 또는 객체의 맵입니다. 값이 string이 아닌 경우 JSON 화됩니다.
So, provide string as parameters. If you don't want that, then use transformations. Again, from the documentation:
To override these transformation locally, specify transform functions as transformRequest and/or transformResponse properties of the config object. To globally override the default transforms, override the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties of the $httpProvider.
Refer to documentation for more details.
Use jQuery's $.param
function to serialize the JSON data in requestData.
In short, using similar code as yours:
$http.post("/foo/bar",
$.param(requestData),
{
headers:
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}
).success(
function(responseData) {
//do stuff with response
}
});
For using this, you have to include jQuery in your page along with AngularJS.
Note that as of Angular 1.4, you can serialize the form data without using jQuery.
In the app.js:
module.run(function($http, $httpParamSerializerJQLike) {
$http.defaults.transformRequest.unshift($httpParamSerializerJQLike);
});
Then in your controller:
$http({
method: 'POST',
url: myUrl',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: myData
});
This might be a bit of a hack, but I avoided the issue and converted the json into PHP's POST array on the server side:
$_POST = json_decode(file_get_contents('php://input'), true);
I have problems as well with setting custom http authentication because $resource cache the request.
To make it work you have to overwrite the existing headers by doing this
var transformRequest = function(data, headersGetter){
var headers = headersGetter();
headers['Authorization'] = 'WSSE profile="UsernameToken"';
headers['X-WSSE'] = 'UsernameToken ' + nonce
headers['Content-Type'] = 'application/json';
};
return $resource(
url,
{
},
{
query: {
method: 'POST',
url: apiURL + '/profile',
transformRequest: transformRequest,
params: {userId: '@userId'}
},
}
);
I hope I was able to help someone. It took me 3 days to figure this one out.
Modify the default headers:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
Then use JQuery's $.param
method:
var payload = $.param({key: value});
$http.post(targetURL, payload);
.controller('pieChartController', ['$scope', '$http', '$httpParamSerializerJQLike', function($scope, $http, $httpParamSerializerJQLike) {
var data = {
TimeStamp : "2016-04-25 12:50:00"
};
$http({
method: 'POST',
url: 'serverutilizationreport',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(data),
}).success(function () {});
}
]);
Quick adjustment - for those of you having trouble with the global configuration of the transformRequest function, here's the snippet i'm using to get rid of the Cannot read property 'jquery' of undefined
error:
$httpProvider.defaults.transformRequest = function(data) {
return data != undefined ? $.param(data) : null;
}
You can also solve this problem without changing code in server, changing header in $http.post
call and use $_POST
the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I found many times problematic behavior of this whole. I used it from express (without typings) and the bodyParser (with the dt~body-parser typings).
I didn't try to upload a file, instead simply to interpret a JSON given in a post string.
The request.body
was simply an empty json ({}
).
After a lot of investigation finally this worked for me:
import { json } from 'body-parser';
...
app.use(json()); <-- should be defined before the first POST handler!
It may be also important to give the application/json
content type in the request string from the client side.
Syntax for AngularJS v1.4.8 + (v1.5.0)
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
Eg:
var url = "http://example.com";
var data = {
"param1": "value1",
"param2": "value2",
"param3": "value3"
};
var config = {
headers: {
'Content-Type': "application/json"
}
};
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
'IT story' 카테고리의 다른 글
.NET 어셈블리에 텍스트 파일을 포함시키는 방법은 무엇입니까? (0) | 2020.07.20 |
---|---|
PuTTY를 통해 Vi (Vim)에서 숫자 키패드 사용 (0) | 2020.07.20 |
특정 문자 또는 문자 집합에 대한 셀 확인 (0) | 2020.07.20 |
재귀는 그 자체로 기능입니까? (0) | 2020.07.20 |
팀 도시 충족되지 않은 요구 사항 : MSBuildTools12.0_x86_Path 존재 (0) | 2020.07.20 |