Loopback post method call

血红的双手。 提交于 2019-12-13 04:10:32

问题


I want to send a post request with loopback "invokeStaticMethod". Please help me how to do it. I want to send a POST API request to below url:

localhost:3000/api/user/id/unblock With parameter {"userId", "blockId"}

Please let me know how can I send a POST request with Loopback


回答1:


You could create a remote method like this:

User.unblock = function(id, userId, blockId, callback) {
  var result;
  // TODO
  callback(null, result);
};

Then, the remote method definition in the json file could look like this:

"unblock": {
  "accepts": [
    {
      "arg": "id",
      "type": "string",
      "required": true,
      "description": "",
      "http": {
        "source": "path"
      }
    },
    {
      "arg": "userId",
      "type": "string",
      "required": false,
      "description": "",
      "http": {
        "source": "form"
      }
    },
    {
      "arg": "blockId",
      "type": "string",
      "required": false,
      "description": "",
      "http": {
        "source": "form"
      }
    }
  ],
  "returns": [
    {
      "arg": "result",
      "type": "object",
      "root": false,
      "description": ""
    }
  ],
  "description": "",
  "http": [
    {
      "path": "/:id/unblock",
      "verb": "post"
    }
  ]
}

Then your remote method would look like this:

You could play around with function arguments and use one body argument instead of 2 form arguments and read the data from there, although I believe that if there are only 2 additional parameters it's better to put them separately. But it depends on your approach.




回答2:


I believe this is what you are looking for...

https://loopback.io/doc/en/lb3/Adding-remote-methods-to-built-in-models.html

In your case, it should look something like this...

module.exports = function(app) {
  const User = app.models.User;

  User.unblock = function(userId, blockId, cb) {
      ... <Your logic goes here> ...
      cb(null, result);
  };

  User.remoteMethod('unblock', {
      accepts: [{arg: 'userId', type: 'string'}, {arg: 'blockId', type: 'string'}],
      returns: {arg: 'result', type: 'string'}
  });


来源:https://stackoverflow.com/questions/49492305/loopback-post-method-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!