Learn REACT with node.js

How to learn JS? For me best way it is practice programing… just write the code like some examples below.

But first some preliminary tasks.

Tools stack

Instal

Install express.js and nodemon

$ npm install express --save
$ npm install nodemon --save

Code

First example is about REST with express.js

Create directory rest and init git repozitory. To add a remote, just do

cd "path to your repo"
git init
git add . # if you want to commit everything. Otherwise use .gitconfig files
git commit -m "initial commit" # If you change anything, you can add and commit again...
var stack = [];
stack.push(2);       // stack is now [2]
stack.push(5);       // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i);            // displays 5

var queue = [];
queue.push(2);         // queue is now [2]
queue.push(5);         // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i); 

Event emitter

Event logger class

const EventEmitter = require('events');

class Logger extends EventEmitter {
    constructor() {
        super();
        this.messageStore = [];
    }

    log(eventArg) {
        console.log('[Logger.log(message)]:', eventArg.id, eventArg.url);
        this.emit('messageLogged', eventArg);
        this.messageStore.push(eventArg.url);
        //console.log(this.messageStore.pop());

        var propValue;
        for (var propName in this.messageStore) {
            propValue = this.messageStore[propName];
            console.log('>', propName, propValue);
        }
    }
}
module.exports = Logger;

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');
var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

So our program will looks like this:

const express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

var app = express();
app.use(express.json());

var courses = [{
    id: 1,
    name: 'course1'
}, {
    id: 2,
    name: 'course2'
}, {
    id: 3,
    name: 'course3'
}, {
    id: 4,
    name: 'course4'
}, {
    id: 5,
    name: 'course5'
}, {
    id: 6,
    name: 'course6'
}];



app.get('/api/courses/:id', function (request, response) {
    var course = courses.find(c => c.id === parseInt(request.params.id));
    if (!course) response.status(404).send(`The course with the given ID ${request.params.id} not exist in courses`);
    response.send(course);
});

app.get('/api/courses', function (request, response) {
    if (courses.length < 1) response.status(404).send('The courses not exist');
    response.send(courses);
});

app.post('/api/courses', upload.array(), (request, response, next) => {
    console.log("Got response: " + response.statusCode);
    console.log('Request body: ', request.body);
    // console.log('request =' + JSON.stringify(request.body))
    if (!request.body.name || request.body.length < 3) {
        response.status(400).send('Name is required and should be sent to in JSON');
        return;
    }
    const course = {
        id: courses.length + 1,
        name: request.params.name
    };

    courses.push(course);
    response.json(request.body);
    response.send(course);
});

app.get('/', function (request, res) {
    res.send('Hello World!');
});

const port = process.env.PORT || 3000;
app.listen(3000, () => console.log(`Listen on port ${port}...`));

Hits: 0

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑