angularjs http post 405 error

Problem

angular http로 data를 담아 post를 날렸다. 헤더엔 넣은 데이터의 json key value값이 잘 들어가있는데(사실 그런것처럼 보이는 것이다) 데이터가 오지 않았다는 에러가 난다.

$http.defaults.xsrfCookieName = 'csrftoken';
        $http.defaults.xsrfHeaderName = 'X-CSRFToken';

        $http.post('/api/stock/'+$('.stock-select').val()+'/'+operationName+'/', {
            inventory: $('.inventory-select').val(),
            quantity: $('.number-select').val()
        }, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(function(res){
            console.log("success", res);
        }, function() {
            alert("error");
        });

Solution

key value가 아닌, json을 통으로 인식해서 생기는 문제이므로, 데이터를 $.param으로 감싸서 보내준다. 앵귤러 웨저러는고야~~

$http.defaults.xsrfCookieName = 'csrftoken';
        $http.defaults.xsrfHeaderName = 'X-CSRFToken';

        $http.post('/api/stock/'+$('.stock-select').val()+'/'+operationName+'/', $.param({
            inventory: $('.inventory-select').val(),
            quantity: $('.number-select').val()
        }), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(function(res){
            console.log("success", res);
        }, function() {
            alert("error");
        });

참고

ajax로 보내기

function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getCookie('csrftoken');

        $.ajax({
            type: 'POST',
            url: '/api/stock/'+$('.stock-select').val()+'/'+operationName+'/',
            data: {
                inventory: $('.inventory-select').val(),
                quantity: $('.number-select').val()
            },
            headers: {
                "X-CSRFToken": csrftoken
            },
            success: function() {
                console.log("success")
            }
        });

Refer

http://stackoverflow.com/questions/27387467/angularjs-http-post-method-405-error

Published by

Yurim Jin

아름다운 웹과 디자인, 장고와 리액트, 그리고 음악과 맥주를 사랑하는 망고장스터

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s