prosource

각도, 컨텐츠 유형이 $http와 함께 전송되지 않습니다.

probook 2023. 2. 8. 18:04
반응형

각도, 컨텐츠 유형이 $http와 함께 전송되지 않습니다.

Angular가 올바른 컨텐츠 유형 옵션을 추가하지 않았습니다. 다음 명령을 시도했습니다.

$http({
    url: "http://localhost:8080/example/teste",
    dataType: "json",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

위의 코드는 다음 http 요청을 생성합니다.

POST http://localhost:8080/example/teste HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/xml
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8080/example/index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=C404CE2DA653136971DD1A3C3EB3725B

보시는 바와 같이 "application/json" 대신 "application/xml" 컨텐츠 유형이 됩니다.내가 뭘 빠트렸나요?

요청에 본문을 포함해야 합니다.Angular를 지정하면 콘텐츠유형 헤더가 삭제됩니다.

더하다data: ''하기 위한 논의에$http.

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

이렇게 해봐.

         $http({
                method: 'GET',
                url:'/http://localhost:8080/example/test' + toto,
                data: '',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(
                function(response) {
                    return response.data;
                }, 
                function(errResponse) {
                    console.error('Error !!');
                    return $q.reject(errResponse);
                }

잘됐네요! 위에서 제시한 솔루션이 효과가 있었어요.같은 문제가 있었습니다.GET불러.

 method: 'GET',
 data: '',
 headers: {
        "Content-Type": "application/json"
 }

누구에게나 유용하게 쓰일 수 있을 것 같아서.AngularJS 1.5x의 경우 모든 요구에 대해 CSRF를 설정하려고 했는데 이 작업을 수행했을 때 다음과 같이 나타났습니다.

$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; 
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; 

Angular가 콘텐츠 유형을 삭제했기 때문에 다음을 추가해야 했습니다.

$httpProvider.defaults.headers.common = { "Content-Type": "application/json"};

그렇지 않으면 415 media type 오류가 발생합니다.

따라서 모든 요구에 대해 응용 프로그램을 설정하기 위해 이 작업을 수행합니다.

angular.module("myapp.maintenance", [])
    .controller('maintenanceCtrl', MaintenanceCtrl)
    .directive('convertToNumber', ConvertToNumber)
    .config(configure);

MaintenanceCtrl.$inject = ["$scope", "$http", "$sce", "$window", "$document", "$timeout", "$filter", 'alertService'];
configure.$inject = ["$httpProvider"];

// configure the header tokens for  CSRF for http operations in this module
function configure($httpProvider) {

    const afToken = angular.element('input[id="__AntiForgeryToken"]').attr('value');

    $httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; // only added for GET
    $httpProvider.defaults.headers.put = { 'CSRF-Token': afToken }; // added for PUT
    $httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; // added for POST

    // for some reason if we do the above we have to set the default content type for all 
    // looks like angular clears it when we add our own headers
    $httpProvider.defaults.headers.common = { "Content-Type": "application/json" };

}

모든 POST 요청에 "Content-type" 헤더를 동적으로 추가하는 방법의 예를 보여 줍니다.POST 파라미터를 쿼리 문자열로 전달하면 transformRequest를 사용합니다.이 경우 값은 application/x-www-form-urlencoded 입니다.

// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}

그런 다음 config 객체를 반환하기 전에 요청 메서드의 대행 수신기에서

// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type']) 
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}

언급URL : https://stackoverflow.com/questions/16194442/angular-content-type-is-not-being-sent-with-http

반응형