1

So, i've been digging for the last two days but i have no idea why this won't work..

here's the problem, i try to make request to an api server and i have to add a token in the request, but when i add the token to header authorization, i've got response 405 from the server

this api i've tested on postman and its work, but when i implement to angular it doesn't work

this my code:

$http({
            method: 'POST',
            url: url,
            data: data,
            headers: {
                "Authorization": "Bearer xxxxxxxxxxx",
                "Content-Type": "application/x-www-form-urlencoded"
            }
        })

and this is the req header from chrome: img

so in this case, is this my code, or the server problem ??

  • One problem i see is that you are doing a form-urlencoded post not the standard json post. The `data` needs to be transformed. See here http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs – Chandermani Apr 21 '16 at 12:17
  • i've transformed the data correctly, if i'm not include header authorization req is work, and result json response form the server, but when i try to add header authorization, it won't work – Hendra Kurniawan Apr 22 '16 at 04:19
  • You can look at the network log for errors. – Chandermani Apr 22 '16 at 06:35
  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9999' is therefore not allowed access. The response had HTTP status code 405. error in chrome console – Hendra Kurniawan Apr 22 '16 at 07:30

1 Answers1

0
  angular
    .module('app')
    .factory('authInterceptor', authInterceptor);
authInterceptor.$inject = ["$q","$location"];
function authInterceptor($q, $location) {
        return {
          // Add authorization token to headers
            request: function (config) {
             // get token from a cookie or local storage
            var token = "token string ";
            config.headers = config.headers || {};
            config.headers.Authorization = "Bearer " + token;
            return config;
          },
          // Intercept 401s and redirect you to login
          responseError: function(response) {

            if(response.status === 401) {
             // redirect to some page

              // remove any stale tokens
              return $q.reject(response);
            }
            else {
              return $q.reject(response);
            }
          }
        };
      }

then inject the interceptor like this

$httpProvider.interceptors.push('authInterceptor');
Mohsin Muzawar
  • 1,202
  • 9
  • 9