2017-06-25 18 views
1

在休耕模式中,我想製作一個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" 
} 

回答

2

很奇怪通過GET請求發送數據,但如果你已經考慮到安全問題,你可以按照如下步驟:

  1. 定義遠程方法:

    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'} 
    }); 
    
  2. 在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!") 
    }); 
    } 
    
  3. 現在,您可以撥打http://localhost:3000/api/shops/create-new-shop?shopname=cafe%20del%20mar&tel=123456&latlng=50.35-56.44&personId=1729451234 注意,分號是保留字符,所以你不能把它作爲一個值的參數,你應該用另一個字符替換它。

+0

tnx,但它顯示了下面的錯誤:。 錯誤 404未知「shop」id「create-new-shop」。 status:404 code:MODEL_NOT_FOUND 錯誤:未知「shop」id「create-new-shop」。 – RSA

+0

更改您的「id」屬性的名稱。 Loopback具有名爲「id」的默認主鍵屬性。也許他們互相干擾。請讓我知道如果問題解決了。 – tashakori

+0

我認爲它與'var shop = new app.models.Shop(instance)'有關,因爲它在explorer中顯示:'「message」:「app is not defined」, 「stack」:「ReferenceError:app is not定義\ n'。在server.js應用程序中已定義 – RSA