-1

I'm new to the AngularJS. I'm using AngularJS 1.3.15 version. When I try to call an api with PUT method, It's generating OPTIONS request. I don't know where I'm doing mistake. I tried so many methods which is suggested in Stockoverflow, but still I'm not getting anything. Please help me to resolve this issue. below are my Controller, Models, html files and Chrome developer tool network activity screenshot.

Controller file users.js

'use strict';
mmlApp_users.config(['$routeProvider', function($routeProvider){
  $routeProvider
    .when('/users/update/:userId', {
      templateUrl: 'views/users/update.html',
      controller: 'update',
      resolve: {
        user: function(users, $route){
          var userId = $route.current.params.userId
          return users.getUser(userId);
        }
      }
    })
    .otherwise({
      redirectTo: '/users/index'
    });
}]);

Model file - users.js

'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route', function($http, $location, $route){
  var obj = {}; 

  obj.getUser = function(userId){
    return $http.get(serviceBase + 'users/view/'+userId);
  };

  obj.updateUser = function(user){
    var config = {
          headers: {
            'Content-Type': 'application/json'
          }
        };
    var userParams = {
        first_name: user.first_name, 
        last_name: user.last_name, 
        email: user.email, 
        password: user.password,
        address: user.address,
        state: user.state,
        city: user.city,
        zip_code: user.zip_code
      };
    $http.put(serviceBase + 'users/update/'+user.id+'?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13', userParams, config)
          .then(successHandler).catch(errorHandler);

    function successHandler(){
      $location.path('/users/index');
    }
    function errorHandler(){
      alert('Oops! Somthing went wrong.');
      //$location.path('/users/create');
    }
  };

  return obj;
}]);

Views - update.html

<div>
  <h1>{{title}}</h1>
  <p>{{ message}}</p>
  <form role="form" name="myForm">
    <div class="row">
      <div class= "form-group col-md-6" ng-class="{error: myForm.first_name.$invalid}">
        <label> First Name: </label>
        <div>
          <input name="first_name" ng-model="user.first_name" type= "text" class= "form-control" placeholder="First Name" required/>
          <span ng-show="myForm.first_name.$dirty && myForm.first_name.$invalid" class="help-inline">First Name Required</span>
        </div>
      </div>
      <div class= "form-group col-md-6" ng-class="{error: myForm.last_name.$invalid}">
        <label> Last Name: </label>
        <div>
          <input name="last_name" ng-model="user.last_name" type= "text" class= "form-control" placeholder="Last Name" required/>
          <span ng-show="myForm.last_name.$dirty && myForm.last_name.$invalid" class="help-inline">Last Name Required</span>
        </div>
      </div>
    </div>
    ....
    ....
    ....

    <a href="#/users/index" class="btn btn-default">Cancel</a>
    <button ng-click="updateUser(user);" ng-disabled="myForm.$invalid" type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

In chrome developer tool network activity screenshot - enter image description here

Manikandan S
  • 902
  • 1
  • 8
  • 18
  • That's just part of sending a CORS request. Fix the server so it handles it properly. – Kevin B Jul 27 '17 at 18:45
  • May I know why this question is down voted? If anything is wrong please tell me I try to correct it next time. – Manikandan S Jul 27 '17 at 18:45
  • lack of research. Nothing in your question seems to indicate that you even know what CORS is. – Kevin B Jul 27 '17 at 18:47
  • Although this is POST and not GET, look at this question: [Why am I getting an OPTIONS request instead of a GET request?](https://stackoverflow.com/questions/1256593/why-am-i-getting-an-options-request-instead-of-a-get-request). – Kevin Jul 27 '17 at 18:47
  • @KevinB for api side i'm using PHP. I already added this header in my api entry file - header('Access-Control-Allow-Origin: *'); – Manikandan S Jul 27 '17 at 18:48
  • that's not enough to handle preflights. Your server is responding with 405, but it needs to instead respond with 200. – Kevin B Jul 27 '17 at 18:49
  • @KevinB please tell me how to handle preflights. I'm not aware of it. – Manikandan S Jul 27 '17 at 18:52
  • @Kevin Thanks for sharing that link. I will check now. – Manikandan S Jul 27 '17 at 18:53
  • it depends on the server unfortunately. – Kevin B Jul 27 '17 at 18:53
  • @KevinB This issue happen only in case of PUT request. But GET and POST is working fine for me. So I hope server or API side not an issue. – Manikandan S Jul 27 '17 at 18:56
  • 1
    Right, CORS has rather strict rules on what requires a preflight and what doesn't. GET and POST requests that don't change the contentType header or otherwise add additional headers don't require a preflight. – Kevin B Jul 27 '17 at 18:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150346/discussion-between-manikandan-s-and-kevin-b). – Manikandan S Jul 27 '17 at 18:58

1 Answers1

-1

try in your factory:

(function () {
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route','$httpParamSerializer',
function ($http, $location, $route, $httpParamSerializer) {

    var obj = {};

    obj.getUser = function (userId) {
        return $http.get(serviceBase + 'users/view/' + userId);
    };

    obj.updateUser = function (user) {

        var userParams = {
            first_name: user.first_name,
            last_name: user.last_name,
            email: user.email,
            password: user.password,
            address: user.address,
            state: user.state,
            city: user.city,
            zip_code: user.zip_code
        };

        var req = {
            method: 'PUT',
            url: serviceBase + 'users/update/' + user.id + '?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            data: $httpParamSerializer(userParams)
        };

        $http(req)
            .then(successHandler)
            .catch(errorHandler);

        function successHandler() {
            $location.path('/users/index');
        }

        function errorHandler() {
            alert('Oops! Somthing went wrong.');
            //$location.path('/users/create');
        }
    };

    return obj;

}]);

})();

And Goog Lock :)