REST APIs 

 Hello World with express

 
import express from 'express';
let app = express();

app.get('/', (req,res) => {
    res.send('Hello World');
    });
app.listen(8080);

Middleware can :

  • make changes to the request and the response objects
  • end the request

body-parser

cookie-parser

cors

express.static

parse request et populate req.body

 

Parse cookie header et populate req.cookies

Allow CORS requests

server static content from the "public" directory ( html, css , js, etc)

Router /

Hello-World

import express from 'express';
const router = express.Router();
router.get("/", (req, res) => {
    res.send('Hello Simplon');
    });
module.exports = router;
import express from 'express';
const app = express();

//routes
app.use("/hello", require('./api-hello'));

app.listen(8080);

api-hello.js

 

index.js

Router /

Why ??

Les routes vont nous permettre de spliter notre code en modules

Mongoose

What is it ?

Mongoose is a Node.js connector for MongoDB.

Connect to MongoDB

import mongoose from 'mongoose';

mongoose.connect('mongodb://localhost/test);

Tout dans Mongoose commence par un schéma. Chaque schéma correspond à une collection MongoDB et définit la forme des documents de cette collection.

Schema

let StudentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    course:[String],
    address: {
    city: String,
    country: String
    }
});

let Student = mongoose.model('Student', StudentSchema);

Définire le format de document avec un schema :

Creation et Mise à jour

let Student = new Student({
    name: 'billy',
    age: 22,
    course:["React","Node.js"],
    address: {
    city: "Paris",
    country: "France"
    }
});

student.save((err) => {
    if (err) return console.log("not saved");
    console.log('saved');

Trouver un item

Student.findOne({name:"billy"}, (err, student) => {
    //student est un Objet
});

REST APIs

Kesako ??!?

REST API

By rodolphe

REST API

  • 447