Michael Pell
Michael Pell

Reputation: 1476

Angular $http post() format Defaults to HTML on Rails

I have a factory that exposes a create() function which uses $http.post() underneath. For some reason when it is called from an ng-click the request is being formatted as HTML. All of the params are where I want them to be, but Rails is processing the request as HTML.

The factory:

orizabaServices.factory('requestTypeFactory', ["$http", function($http){
    var urlBase = '/request_types';
    var requestTypeFactory = {};

    requestTypeFactory.create = function(params){
      data = {};
      data.authenticity_token =  $("meta[name='csrf-token']").attr("content");
      data.request_type = params;
      return $http.post(urlBase, data)
    };

    return requestTypeFactory;
  }
])

The Error:

Started POST "/request_types" for 127.0.0.1 at 2014-08-01 17:10:00 +0000
Processing by RequestTypesController#create as HTML

Upvotes: 0

Views: 100

Answers (3)

gabrimac
gabrimac

Reputation: 526

You can specify the format of the request adding '.json' to your urlBase. For example:

var urlBase = '/request_types.json';

Upvotes: 2

Māris Cīlītis
Māris Cīlītis

Reputation: 173

It's because by default rails is considerng all requests as HTML. You can change this behaviour in your config/routes.rb file like this:

resources :request_types, :defaults => {:format => 'json'}

Upvotes: 0

KevinS
KevinS

Reputation: 1

You need to add "full URL" for urlBase. If you request POST method on your local machine

var urlBase = 'http://127.0.0.1/request_types'; 

try this

Upvotes: 0

Related Questions