[Tutorial] An Introduction to Node.js Servers (and Express.js)

AJAX

AJAX works with node in a similar way as PHP. In PHP the steps would look almost the same, but just with different syntax. I’ll write an example below.

If you start the node server and visit localhost:3333/api (after making sure the API route from the example repo has been added) it should return some JSON. You can fetch that JSON with AJAX by opening the browser console while on a localhost:3333 page and typing:

fetch("/api")
    .then(res => res.json())
    .then(json => console.log("here is the JSON response", json));

and it should print out the JSON response from the server.

sudo

If the terminal asks for sudo when installing npm packages, Node probably isn’t set up correctly. I’m guessing that Node wasn’t installed with nvm. If you want to fix it (possible security risk), send me a chat message and I could walk through the steps on how to uninstall and reinstall node using nvm.

require

I think in PHP it would be more like use, but I haven’t used much PHP in years and don’t remember the syntax. I think include injects the entire other PHP file into the current file, while use or require just imports specific functions that are allowed to be exported from the other file.

PHP server

You can compare the Express code with modern PHP code by looking at a similar framework for PHP called Slim.

I added some comments to their sample code from the homepage:

<?php
// This is like `require` in Node. Each line imports some functionality
// from another PHP library. In Node, the file that lists the
// dependencies is called `package.json`. In PHP, it's called
// `composer.json`. Here, it's importing `Request` and `Response` as
// well as `AppFactory`, which is like the Node.js line that requires
// `express`.
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

// This is PHP code to load the dependencies.
require __DIR__ . '/../vendor/autoload.php';

// This is like `const app = express()` in Node/Express
$app = AppFactory::create();

// This is like the `app.get("/hello", function(request, response) ...` lines in Express.
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

// This is like `app.listen(...)` in Express code
$app->run();

Nearly all major languages let you create servers with similar steps: Python/Flask, Ruby/Sinatra, etc.

1 Like