change Content-type to "application/json" POST method, RESTful API

Assuming you are able to use one of the more recent "unstable" releases, the correct syntax to change the header is.

app.factory('BarService', function ($resource) {
var BarService = $resource('/foo/api/bars/:id', {}, {    
    'delete': {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    }
});
 return BarService;
});

I find the $resource service is a tremendously powerful tool for building applications and has matured to a point that you do not need to fall back to $http as much. Plus its active record like patterns are damn convenient.


The right way to set 'Content-Type': 'application/json' is setting a transformRequest function for the save action.

angular.module('NoteWrangler')
.factory('NoteNgResource', function NoteNgResourceFactory($resource) {

    // https://docs.angularjs.org/api/ngResource/service/$resource

    return $resource("./php/notes/:id", {}, {
        save : { // redefine save action defaults
            method : 'POST',
            url : "./php/notes", // I dont want the id in the url
            transformRequest: function(data, headers){
                console.log(headers);
                headers = angular.extend({}, headers, {'Content-Type': 'application/json'});
                console.log(headers);
                console.log(data);
                console.log(angular.toJson(data));
                return angular.toJson(data); // this will go in the body request
            }               
        }
    });
});

It seems there isn't a method to clear query parameters, the request will have both...


Posting a JSON object is quite easy in Angular. All you need to do is the following:

Create a Javascript Object

I'll use your exact properties from your code.

var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";

Post the object to the API

To post an object to an API you merely need a simple $http.post function. See below:

$http.post("/path/to/api/", postObject).success(function(data){
    //Callback function here.
    //"data" is the response from the server.
});

Since JSON is the default method of posting to an API, there's no need to reset that. See this link on $http shortcuts for more information.

With regards to your code specifically, try changing your save method to include this simple post method.

Tags:

Angularjs