【问题标题】:AngularJS $resource 'GET' accesses the correct API, but 'PUT' and 'POST' do notAngularJS $resource 'GET' 访问正确的 API,但 'PUT' 和 'POST' 没有
【发布时间】:2013-11-04 00:14:51
【问题描述】:

AngularJS $resource calls the wrong API URL when using method:POST跟进

我的控制器是这样设置的,使用 Angular 的 $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
  }); 

我的服务器在NodeJSExpressJS 上运行。在我的控制台中,当调用save 操作时,我可以看到:

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

但是,我的 API 没有被正确访问。例如,如果我在浏览器中访问上述 URL,则调用 API 函数,并更新我的数据库(并在我的服务器控制台中报告)。然而,当 Angular 在这个 URL 上执行 PUT 时,什么都没有发生。

有趣的是,当我将$scope.updateProduct.save() 更改为$scope.updateProduct.get() 时,API 被正确调用并且一切正常。

有什么想法吗?

编辑:这是服务器设置:

ExpressJS API 设置:

 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})
        }
    });
};

【问题讨论】:

  • 你能显示你服务器的代码吗?
  • 我可以,但根本无法访问,第一行是console.log("TEST"),无法访问。同样,当我使用 updateProduct.get() 而不是 updateProduct.save() 它工作得很好(所以 console.log() 正确记录)
  • 我认为你的服务器路由可能有问题。
  • 好的,将其添加到上面的代码中。
  • 你在哪里告诉 ExpressJS export.updateProduct 正在等待 POST 或 PUT?看看 ExpressJS API,它们引用 app.VERB(path, [callback...], callback) 其中动词是请求的方法。在这里你告诉它等待 GET。

标签: javascript node.js api angularjs angular-resource


【解决方案1】:

您的服务器似乎不是在等待 POST 或 PUT 请求,而是根据您的配置等待 GET 请求。

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

根据 ExpressJS API (http://expressjs.com/api.html),您应该能够将 get 替换为任何有效的 http 动词。

app.VERB(path, [callback...], callback)
app.post('/api/updateProduct/:product/:param/:value', api.updateProduct);
app.put('/api/updateProduct/:product/:param/:value', api.updateProduct);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2016-08-02
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多