Pregunta

Follow up from AngularJS $resource calls the wrong API URL when using method:POST

My controller is set up like this, with Angular's $resource:

$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{},{
  query: {method:'GET'},
  post: {method:'POST'},
  save: {method:'PUT', params: {brand: '@brand', param:'@param', value:'@value'}},
  remove: {method:'DELETE'}
});
$scope.updateProduct.save({
    product : $scope.post._id, 
    param: 'likes', 
    value: $scope.user._id
  }); 

My server runs on NodeJS and ExpressJS. In my console, when the save operation is called, I can see:

POST /api/updateBrand/<productid>/likes/fun,%20quirky%20loud,%20boho,%20hippy 200 22ms - 2.31kb

However, my API is not being correctly accessed. For instance, if I go to the above URL in my browser, the API function is called, and my database is updated (and it is reported in my server's console). Yet when Angular does a PUT on this URL, nothing happens at all.

Interestingly, when I change $scope.updateProduct.save() to $scope.updateProduct.get(), the API is correctly called and everything works fine.

Any ideas what's going on here?

EDIT: Here's the server setup:

ExpressJS API setup:

 app.get('/api/updateProduct/:product/:param/:value', api.updateProduct);

API code

exports.updateProduct = function (req, res) {
    console.log("TEST")

    var product = req.params.product;
    var param   = req.params.param;
    var value   = req.params.value;
    var props = { $push: {} };

    if(param == 'userTags'){
        var oldVal = value;
        value = oldVal.match(/[-'"\w]+/g);
        props.$push[param];
        props.$push[param] = {$each: []};
        props.$push[param].$each = value;
    }else{
    var props = { $push: {} };
        props.$push[param] = value;       
    }
    db.products.update({"_id": ObjectId(product)}, props, function (err, record) {
        if (err || !(record)) {
            console.log("Lookup Error: " + err);
        } else{
            console.log("Updated " + product + " with " + param);
            console.log(record);
            res.json({obj:record})
        }
    });
};
¿Fue útil?

Solución

It seems that your server is not waiting for a POST or PUT request, but a GET request as per your configuration.

app.get('/api/updateProduct/:product/:param/:value', api.updateProduct);

According to the ExpressJS API (http://expressjs.com/api.html), you should be able to replace the get with any valid http verb.

app.VERB(path, [callback...], callback)
app.post('/api/updateProduct/:product/:param/:value', api.updateProduct);
app.put('/api/updateProduct/:product/:param/:value', api.updateProduct);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top