This is a solution for a little test that I do.
Install a sailsjs api
Create a new project. Choose an Empty Sails app
Create a simple action2
Edit config/routes.js
add new route below of api endpoints.
To verify it’s all is ok.. start application,
Open the web browser and on url bar type localhost:1337/getApi. Then you will see an ok.
Install node-fetch to use fetch and get the result of Github api.
Edit api/controllers/get-api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const fetch = require('node-fetch');
module.exports = {
friendlyName: 'Get api',
description: '',
inputs: {},
exits: {},
fn: async function(inputs, exits) {
fetch('https://api.github.com/users/luisreinoso/repos')
.then(apiRes => apiRes.json()) // parse Response to json
.then(repos => {
let nameRepos = [];
repos.forEach(repo => nameRepos.push(repo.name));
sails.log.info(nameRepos);
return exits.success({ nameRepos: nameRepos });
})
.catch(error => {
sails.log.error(error);
return exits.serverError();
});
}
};
To verify it’s all is ok.. re-start application,
Open the web browser and on url bar type localhost:1337/getApi. Then you will see my repos name.
Notes
- fetch is not in node by default
- sails has simple controllers and actions2 to write the api logic
References
- https://www.npmjs.com/package/node-fetch