问题
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