Loopback post method call

2019-09-02 08:41发布

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

2条回答
该账号已被封号
2楼-- · 2019-09-02 09:10

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: enter image description here

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.

查看更多
劫难
3楼-- · 2019-09-02 09:15

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'}
  });
查看更多
登录 后发表回答