데이터를 요청 페이로드가 아닌 폼 데이터로 게시하려면 어떻게 해야 합니까?
가 Angular로 있습니다.JS$http
「URL」 「xsrf」 「Request Payload」(크롬)$.ajax
메서드는 동일한 호출을 수행하지만 xsrf를 "폼 데이터"로 전송합니다.
Angular를 만드는 방법JS는 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
갱신하다
Angular가 추가된 새 서비스를 사용하려면JS V1.4, 참조
솔루션에서 jQuery를 사용하지 않으려면 이 방법을 시도해 보십시오.솔루션은 https://stackoverflow.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 () {});
몇개 깔끔한 , 것을 요..config()
angular.display 을 、 출출의의의 의의의
.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("&");
});
}]);
Angular'에서는 JS v1.4.0이 내장되어 있습니다.$httpParamSerializer
docs 페이지에 나열된 규칙에 따라 임의의 개체를 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 성 property property property 。
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
이러한 답변은 미친 과잉 살상처럼 보입니다. 때로는 단순한 것이 더 낫습니다.
$http.post(loginUrl, "userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password"
).success(function (data) {
//...
아래 솔루션을 사용해 보십시오.
$http({
method: 'POST',
url: url-post,
data: data-post-object-json,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var key in obj) {
if (obj[key] instanceof Array) {
for(var idx in obj[key]){
var subObj = obj[key][idx];
for(var subKey in subObj){
str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
}
}
}
else {
str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
}
}
return str.join("&");
}
}).success(function(response) {
/* Do something */
});
게시용 어댑터 서비스 생성:
services.service('Http', function ($http) {
var self = this
this.post = function (url, data) {
return $http({
method: 'POST',
url: url,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
}
})
컨트롤러 등에서 사용합니다.
ctrls.controller('PersonCtrl', function (Http /* our service */) {
var self = this
self.user = {name: "Ozgur", eMail: null}
self.register = function () {
Http.post('/user/register', self.user).then(function (r) {
//response
console.log(r)
})
}
})
이것과 그 외의 관련 사항에 대해 설명하는 매우 좋은 튜토리얼이 있습니다.- AJAX Forms 제출: AngularJS 웨이
기본적으로 폼 데이터를 URL 인코딩된 문자열로 전송함을 나타내도록 POST 요청의 헤더를 설정하고 데이터를 동일한 형식으로 전송하도록 설정해야 합니다.
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
});
여기서 jQuery의 param() 도우미 함수는 데이터를 문자열로 직렬화하기 위해 사용되지만 jQuery를 사용하지 않는 경우에도 수동으로 수행할 수 있습니다.
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
꼭 체크 아웃해주세요!https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
Symfony2 사용자의 경우:
이를 위해 Javascript에서 아무것도 변경하지 않으려면 symfony 앱에서 다음과 같이 수정할 수 있습니다.
Symfony\Component\를 확장하는 클래스를 만듭니다.HttpFoundation\Request 클래스:
<?php
namespace Acme\Test\MyRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class MyRequest extends Request{
/**
* Override and extend the createFromGlobals function.
*
*
*
* @return Request A new request
*
* @api
*/
public static function createFromGlobals()
{
// Get what we would get from the parent
$request = parent::createFromGlobals();
// Add the handling for 'application/json' content type.
if(0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/json')){
// The json is in the content
$cont = $request->getContent();
$json = json_decode($cont);
// ParameterBag must be an Array.
if(is_object($json)) {
$json = (array) $json;
}
$request->request = new ParameterBag($json);
}
return $request;
}
}
이제 app_dev.php(또는 사용하는 인덱스 파일)의 클래스를 사용합니다.
// web/app_dev.php
$kernel = new AppKernel('dev', true);
// $kernel->loadClassCache();
$request = ForumBundleRequest::createFromGlobals();
// use your class instead
// $request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Content-Type을 설정합니다. 내내 전전 url이 url url 인인인 。 $http.post(url, jQuery.param(data))
현재 Angular에서 찾은 다음 솔루션을 사용하고 있습니다.JS 구글 그룹
$140.postflash/module/json/', 'json=' + 인코딩요동성분(각선)ToJson(데이터), {헤더: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}}).성공(기능(데이터) {$125.data = 데이터;});
2 컴포넌트의 와 같은 것을 .Request::createFromGlobals()
$_POST는 POST를 사용합니다.
AngularJS는 http-request 헤더 내에서 다음 content-type을 수행하므로 올바르게 동작하고 있습니다.
Content-Type: application/json
저와 같은 php를 사용하시거나 Symfony2를 사용하시더라도, 여기 기술된 바와 같이 json 표준에 대한 서버 호환성을 간단히 확장할 수 있습니다.http://silex.sensiolabs.org/doc/cookbook/json_request_body.html
Symfony2 방법(예: Default Controller 내부):
$request = $this->getRequest();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
var_dump($request->request->all());
장점은 jQuery param을 사용할 필요가 없고 Angular를 사용할 수 있다는 것입니다.JS는 이러한 요청을 수행하는 네이티브 방식입니다.
완전한 답변(각 1.4 이후).de de de dependency $httpParamSerializer를 포함해야 합니다.
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
앱 구성에서 -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
자원 요청 시 -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
이는 직접적인 답변이 아니라 약간 다른 디자인 방향입니다.
데이터를 폼으로 게시하지 않고 서버 측 개체에 직접 매핑할 JSON 개체로 게시하거나 REST 스타일 경로 변수를 사용하십시오.
XSRF 키를 전달하려고 하기 때문에 두 옵션 모두 적합하지 않을 수 있습니다.다음과 같은 경로 변수에 매핑하는 것은 끔찍한 설계입니다.
http://www.someexample.com/xsrf/{xsrfKey}
왜냐하면 원래 xsrf 키를 다른 경로에도 전달하고 싶기 때문입니다./login
,/book-appointment
예쁜 URL을 망치고 싶지 않은 경우 등입니다.
흥미롭게도 오브젝트 필드로 추가하는 것도 적절하지 않습니다.서버에 전달하는 각 json 오브젝트에서 필드를 추가해야 하기 때문입니다.
{
appointmentId : 23,
name : 'Joe Citizen',
xsrf : '...'
}
도메인 개체와 직접적인 의미 관계가 없는 다른 필드를 서버측 클래스에 추가하고 싶지 않습니다.
제 생각에 xsrf 키를 전달하는 가장 좋은 방법은 HTTP 헤더를 사용하는 것입니다.많은 xsrf 보호 서버 측 웹 프레임워크 라이브러리가 이를 지원합니다.예를 들어 Java Spring에서는 헤더를 사용하여 전달할 수 있습니다.
JS 오브젝트를 UI 오브젝트에 바인드하는 Angular의 뛰어난 기능은 폼을 일괄적으로 게시하는 관행을 없애고 대신 JSON을 게시할 수 있다는 것을 의미합니다.JSON은 서버측 오브젝트로 쉽게 디시리얼라이즈 할 수 있으며 맵, 어레이, 네스트된 오브젝트 등 복잡한 데이터 구조를 지원합니다.
폼 페이로드에 어레이를 게시하려면 어떻게 해야 합니까?아마 이렇게 될 거야:
shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday
또는 다음과 같습니다.
shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday
둘 다 디자인이 좋지 않습니다.
로그인 데이터를 폼 데이터로 API에 전송해야 하고 Javascript Object(userData)가 URL 인코딩 데이터로 자동 변환됩니다.
var deferred = $q.defer();
$http({
method: 'POST',
url: apiserver + '/authenticate',
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: userData
}).success(function (response) {
//logics
deferred.resolve(response);
}).error(function (err, status) {
deferred.reject(err);
});
내 사용자 데이터는 다음과 같습니다.
var userData = {
grant_type: 'password',
username: loginData.userName,
password: loginData.password
}
$http 개체를 생성할 때 "data"가 아닌 "params" 속성을 사용해야 합니다.
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
위의 예에서 clients[i]는 JSON 객체일 뿐입니다(어떤 방법으로도 시리얼화되지 않습니다).data가 아닌 params를 사용하면 angular는 $httpPParamSerializer를 사용하여 개체를 시리얼화합니다.https://docs.angularjs.org/api/ng/service/$httpParamSerializer
각도 사용JS$http
서비스 및 사용post
메서드 또는 설정$http
기능.
언급URL : https://stackoverflow.com/questions/11442632/how-can-i-post-data-as-form-data-instead-of-a-request-payload
'programing' 카테고리의 다른 글
중력 형태 - 다중 사이트용 전역 형태 (0) | 2023.02.14 |
---|---|
XMLHttpRequest 중에 Chrome의 로드 표시기가 계속 회전합니다. (0) | 2023.02.14 |
componentWillReceiveProps 라이프 사이클 메서드를 사용하는 경우 (0) | 2023.02.14 |
안심 - 응답 JSON을 목록으로 역직렬화 (0) | 2023.02.10 |
Azure: MySQL in-app(미리보기)를 사용하는 Wordpress 데이터베이스의 기본 사용자/패스 위치는 어디입니까? (0) | 2023.02.10 |