Search code examples
angularjsnode.jsangular-resource

POST request using angular $resource


In my index.js file I have the following POST...

router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {

    var bear = new Bear();      // create a new instance of the Bear model
    bear.name = req.body.name;  // set the bears name (comes from the request)

    // save the bear and check for errors
    bear.save(function(err) {
        if (err)
            res.send(err);

        res.json({ message: 'Bear created!' });
    });

})
.get(function(req, res) {
    Bear.find(function(err, bears) {
        if (err)
            res.send(err);

        res.json(bears);
    });
});

I test the url http://localhost:8080/api/bears with a POST request on Postman and it was successful. Now I'd like to test my POST request using angular $resource.

I tried the following which I got from the documentation...

app.factory('Profile', function ($resource) {
    var Bear = $resource('http://XXX.XXX.X.XX:3000/api/bears/:bearId', {bearId:'@id'});
    var single_bear = Bear.post({bearId:123}, function(){
        single_bear.name = "Yogi";
        single_bear.$save();
    });
});

I'm not sure what I should for bearId, I just put a random number. And I am trying to save the bear's name as Yogi. I'm assuming this POST request will occur when I run the app, but I do so and then check to see if my db was filled and there is no entry.

What am I doing wrong?

EDIT

in case you're wondering what a bear entry looks like...

{
    "_id": "57ded2302a5ebc050ce3852d",
    "__v": 0,
    "name": ""
 }

Solution

  • Your resource is configured to look for the id property in the data passed (via '@id') yet your data is passing bearId.

    Additionally, the data from your server seems to have an _id property, not id nor bearId.

    Also, the resource method you're looking for is save(), not post().


    I'd go with this type of resource definition...

    $resource('http://XXX.XXX.X.XX:3000/api/bears/:id', {id:'@_id'});
    

    Then, you can use it to create a new Bear via

    Bear.save({_id: 123, name: 'Yogi'})