如何使一个web服务通过环回在mongodb中通过url发送数据?
问题描述:
在休耕模式中,我想制作一个Web服务来发送数据并将其保存到数据库中。如何使一个web服务通过环回在mongodb中通过url发送数据?
localhost:3000/api/shops/shopname=cafe del mar&tel=123456&latlng=50.35;56.44&personId=1729451234
商店模型
{
"shopname": "string",
"tel": "string",
"latlng": "string",
"address": "string",
"id": "string",
"personId": "string"
}
答
很奇怪通过GET请求发送数据,但如果你已经考虑到安全问题,你可以按照如下步骤:
-
定义远程方法:
Shop.remoteMethod('createNewShop',{ accepts: [{arg: 'shopname', type: 'string'}, {arg: 'tel', type: 'string'}, {arg: 'latlng', type: 'string'}, {arg: 'address', type: 'string' }, { arg: 'id', type: 'string'}, { arg: 'personId', type: 'string' } ], returns: {arg: 'result', type: 'string'}, http: {path: '/create-new-shop', verb: 'get'} });
-
在shop.js文件落实createNewShop功能:
var app = require ("../../server/server"); Shop.createNewShop =function(shopname, tel, latlng, address, id, personId, cb){ var instance = { shopname: shopname, tel: tel, latlng: latlng, address: address, id: id, personId: personId } var shop = new app.models.Shop(instance) shop.save().then(function(savedShop,err){ if(err) throw err else cb (null, "done!") }); }
现在,您可以拨打http://localhost:3000/api/shops/create-new-shop?shopname=cafe%20del%20mar&tel=123456&latlng=50.35-56.44&personId=1729451234 注意,分号是保留字符,所以你不能把它作为一个值的参数,你应该用另一个字符替换它。
tnx,但它显示了下面的错误:。 错误 404未知“shop”id“create-new-shop”。 status:404 code:MODEL_NOT_FOUND 错误:未知“shop”id“create-new-shop”。 – RSA
更改您的“id”属性的名称。 Loopback具有名为“id”的默认主键属性。也许他们互相干扰。请让我知道如果问题解决了。 – tashakori
我认为它与'var shop = new app.models.Shop(instance)'有关,因为它在explorer中显示:'“message”:“app is not defined”, “stack”:“ReferenceError:app is not定义\ n'。在server.js应用程序中已定义 – RSA