Documentos de Académico
Documentos de Profesional
Documentos de Cultura
es/blog/como-crear-una-api-rest-usando-node-js/
45 10
1 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
$ mkdir node-api-rest-example
2 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
$ brew update
$ brew install node
package.json
package.json
{
"name": "node-api-rest-example",
"version": "2.0.0",
"dependencies": {
"mongoose": "~3.6.11",
"express": "^4.7.1",
"method-override": "^2.1.2",
"body-parser": "^1.5.1"
}
}
3 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
app.js
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
4 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
http
bodyParser methodOverride()
app.route(nombre_de_la_ruta)
.get() .post() …
express.Router()
GET Hello World
$ node app.js
Node server running on http://localhost:3000
5 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
$ git add .
$ git commit -m 'Initial commit'
models/tvshow.js
6 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
app.j
app.use(router);
7 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
$ brew update
$ brew install mongodb
$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log
node app.js
$ node app.js
Node server running on http://localhost:3000
Connected to Database
8 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
$ mongo
MongoDB shell version: 2.4.1
connecting to: test
> use tvshows
switched to db tvshows
> show dbs
local 0.078125GB
tvshows (empty)
>_
controllers/tvshows.js exports
//File: controllers/tvshows.js
var mongoose = require('mongoose');
var TVShow = mongoose.model('TVShow');
9 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
console.log('GET /tvshows')
res.status(200).jsonp(tvshows);
});
};
findAllTVShows
tvshows
find() findById()
10 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
year: req.body.year,
country: req.body.country,
poster: req.body.poster,
seasons: req.body.seasons,
genre: req.body.genre,
summary: req.body.summary
});
tvshow.save(function(err, tvshow) {
if(err) return res.status(500).send( err.message);
res.status(200).jsonp(tvshow);
});
};
tvshow
.save()
11 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
.findById()
.remove()
.save()
app.js
// API routes
12 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
tvshows.route('/tvshows')
.get(TVShowCtrl.findAllTVShows)
.post(TVShowCtrl.addTVShow);
tvshows.route('/tvshows/:id')
.get(TVShowCtrl.findById)
.put(TVShowCtrl.updateTVShow)
.delete(TVShowCtrl.deleteTVShow);
app.use('/api', tvshows);
13 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
{
"title": "LOST",
"year": 2004,
"country": "USA",
"poster": "http://ia.media-imdb.com/images/M/MV5BMjA3NzMyMzU1MV5BMl5BanBnXkFtZTc
"seasons": 6,
"genre": "Sci-Fi",
"summary": "The survivors of a plane crash are forced to live with each other on
}
SEND
14 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
mongod
$ mongo
MongoDB shell version: 2.4.1
connecting to: test
> show databases
tvshows 0.203125GB
> use tvshows
switched to db tvshows
> show collections
system.indexes
tvshows
> db.tvshows.find()
{ "title" : "LOST", "year" : 2004, "country" : "USA", "poster" : "http://ia.media-
http://localhost:3000/tvshows
15 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
GET
tvshows/:id
16 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
45 10
17 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
18 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
41 Comentarios 1
alx_lopz •
Hola carlos quisiera saber como habilito CORS ya que mi navegador me lanza este error
en consola: "XMLHttpRequest cannot load http://api.midominio/colores. No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin
'http://localhost:9000' is therefore not allowed access". Subí mi api a un server con nginx,
si entro a api.midominio/colores si me despliega el json en crudo, pero cuando lo conecto
en mi app angular no carga los valores y me lanza dicho error.
• •
Hola @alx_lopz
Eso puedes arreglarlo con este paquete: https://www.npmjs.com/package/... e
indicando la URL donde tienes tu app angular :)
Saludos!
• •
Luca Enzô •
Frank •
Yo cuando trato de hacer un tutorial tuyo no me sale nunca, no sé que clase de brujeria
es esta pero igual gracias por los tutoriales. ptt: me perdí ya que no agregaste en el
app.js el modelo de tvshow, luego tratas de hacer el tutorial que tienes hecho en youtube
y resulta que es de una versión antigua de express y tampoco funciona.
• •
VooDoo •
Hola Carlos, excelente tutorial! Me ha resultado muy muy util, funciona todo genial.
Aun asi, hay un pequeño detalle que no me va bien. Mi intencion es usar dos modelos a
la vez (en la misma base de datos). Comparandolo con tu caso seria base de datos
"tvshows" y modelos "tvshows" y "weather". Siguiendo tu ejemplo no parece complicado,
simplemente he añadido en el fichero "controllers/tvshows" la sentencia:
19 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/
20 of 20 3/26/2016 11:18 PM