【问题标题】:How to implement custom routes in sailsjs如何在sailsjs中实现自定义路由
【发布时间】:2015-07-21 20:07:24
【问题描述】:

我正在尝试理解sails.js。首先,我尝试生成新的 api。 这是我的模型和控制器代码

Coutries.js

module.exports = {

  attributes: {
    title:{
        type:'string',
        unique:true,
        primaryKey:true
    },

    cities:{
        collection:'Cities',
        via:'country'
    }
  }
};

城市,js

module.exports = {

  attributes: {
    title: {
      type:'string',
      unique:true,
      primaryKey:true
    },
    country:{
        model:'Countries',
        type:'String'
    },
    description: {
        type:'string'
    }
  }
};

接下来在我写的 routes.js 中

'get /countries':'CountriesController.getAllCountries'

我需要一份国家/地区列表。 我无法理解如何在 CountryController.js 中实现函数 getAllCountries。 我在 tmp 目录中使用本地数据库。 拜托,有人可以详细了解我该怎么做吗? 也为了理解告诉我如何实现一个函数 addNewCountries 和例如 updateCitiesDescription。

感谢和抱歉我的英语)

【问题讨论】:

    标签: javascript sails.js


    【解决方案1】:

    使用sails,如果你有一个函数来处理你的路线,你可以在api/controllers/CountriesController中创建它作为一个方法。

    路线:

    'get /countries':'CountriesController.getAllCountries'
    

    国家/地区控制器:

    module.exports = {
      getAllCountries: function (req, res, next){
        return Country.getAllCountries(function success(countries){
          //handle your success logic e.g: return res.view("countries", {data: countries});
        }, function errorHandle(error){
          //error handling
        })
      }
    
    }
    

    国家模式:

    //inside your module.exports in api/models/Countries add this method
    getAllCountries: function(cb, err){
      Country.find({}).then(cb).catch(err);
    }
    

    总而言之,您使用控制器方法联系模型并传递成功和错误处理函数,这些函数将返回适当的视图。

    【讨论】:

    • 谢谢。我明白这一点。其实我不明白这部分的实现:return countries.findAll({ //query details },
    【解决方案2】:

    好吧,如果您的目标只是查看国家/地区列表,那么 Sails 可以满足您的需求。它提供了蓝图 API,您可以直接使用它来查询您的数据库并以 JSON 格式查看响应。

    例如,你可以调用

    http://localhost:1337/countries
    

    查看数据库中的所有国家。同样,您也可以直接使用 API 执行其他查询。查找有关它的更多信息here

    但是,如果您仍想自己查询数据库以掌握其中的窍门,那么到目前为止您所做的一切都是正确的。

    在您的国家控制器中,创建一个名为“getAllCountries”的新操作

    getAllCountries: function(req, res) {
       Countries.find().exec(function(err, countries){
         res.json(countries);
       });
    });
    

    您的路由基本上会尝试在控制器“CountriesController”中找到一个名为“getAllCountries”的方法,并将您的请求重定向到该操作。

    收到电话后,您只需使用 waterline 的 query language 从数据库中获取国家/地区列表,然后将 JSON 返回给用户。

    一个友好的建议,避免以复数形式命名你的模型。例如,如果您尝试在数据库中维护国家和城市,则将模型命名为“Country”和“City”。

    【讨论】:

      猜你喜欢
      • 2014-09-16
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多