First of all, make sure you have Node installed on your computer, I'd recommend using NVM. Then create a new folder and make a "index.js" file with the following contents.
const http = require('http');
const server = http.createServer((request, response) => {
response.end('hello');
});
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code using node index.js
in your terminal and go to "http://127.0.0.1:1337/" in your browser. You should see "hello". You can now stop the server by entering ctrl+c in your terminal (from now on you'll need to do this before running your code).
So this is pretty great, but what you probably want is to return a HTML file. So create an "index.html" file with the following contents.
<html>
<body>
Hello Mushrooms
</body>
</html>
Now we need to change the "index.js" file to send back the "index.html" file.
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again and refresh your browser. You should see your "index.html" file rendered beautifully in your browser.
Again this is great, but most websites also have an API, so when we send requests to /api/hello
let's return a "hello" message", but when we go to /
let's keep returning the "index.html".
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {
if (request.url === '/api/hello') {
response.end('Hello');
} else {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
}
});
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again and refresh your browser. You should still see your "index.html" file rendered. Now go to "http://127.0.0.1:1337/api/hello" and you should "Hello" in your browser instead.
So now you've served a HTML file for your user interface and created a little API. However, if we wanted to add more routes to our API this will get kind of messy with a lot of if
statements. Luckily, Express helps you with this, Express is a package that we install from the NPM (Node Package Manager) registry with npm i express
. We can then recreate our server using Express with the code below.
const http = require('http');
const fs = require('fs');
const express = require('express');
const expressApp = express();
expressApp.get('/api/hello', (request, response) => {
response.end('Hello');
});
expressApp.get('/', (request, response) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
const server = http.createServer(expressAPp);
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again. When you go to "http://127.0.0.1:1337/api/hello" you should still see "Hello" and when you go to "http://127.0.0.1:1337/" you should still see your rendered HTML file.
Alright now some parts of your API will need to accept some variables via query parameters for example. So let's change our "/api/hello" route to accept a name
in the query parameters so that we can say hello with someone's name.
const http = require('http');
const fs = require('fs');
const express = require('express');
const expressApp = express();
expressApp.get('/api/hello', (request, response) => {
response.end(`Hello ${req.query.name}`);
});
expressApp.get('/', (request, response) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
const server = http.createServer(expressAPp);
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again. Now, when you go to "http://127.0.0.1:1337/api/hello?name=Bob" your browser should display "Hello Bob".
So far we've only used HTTP GET requests (when you navigate to a URL in your browser that's a GET request). Usually APIs also support other HTTP methods (POST, PUT, DELETE, etc). So let's change our "/api/hello" route to accept some JSON in a POST request and send some JSON back with a message. Firstly we'll want to install the body-parser
module from NPM using npm i body-parser
, this will make handling the request body much easier.
const http = require('http');
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const expressApp = express();
expressApp.use(bodyParser.json());
expressApp.get('/api/hello', (request, response) => {
response.json({
message: `Hello ${request.body.name}`
});
});
expressApp.get('/', (request, response) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
const server = http.createServer(expressAPp);
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again. Then go to Postman, create a POST request to "http://127.0.0.1:1337/api/hello" and set the body to use JSON with content like { "name": "Bob" }
. When you hit "send" you should see a JSON response like { "message": "Hello Bob" }
.
This is starting to get pretty cool, so we've dealt with receiving and sending JSON now, but what about receiving and storing files, that's a pretty common server task. Let's modify our "/api/hello" route again and let's stream the request body into a file called "data.txt".
const http = require('http');
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const expressApp = express();
expressApp.use(bodyParser.json());
expressApp.get('/api/hello', (request, response) => {
request.pipe(fs.createWriteStream('./data.txt'));
response.end('Completed');
});
expressApp.get('/', (request, response) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
const server = http.createServer(expressAPp);
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Run the code again. Then go back to Postman and change the body to use text with content like Hello Bob
. When you hit "send" you should see a response that says "Completed" and you should also find "Hello Bob" stored in a newly created "data.txt" file.
Nice! Now you can store files! What about storing data to a database? Let's change our "/api/hello" route again to accept a JSON body that contains some data to insert into Mongo. Firstly we'll need to install the Node MongoDB driver using npm i mongodb
, then we can change the code as shown below.
const http = require('http');
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const expressApp = express();
expressApp.use(bodyParser.json());
expressApp.post('/api/hello', async (req, res) => {
const client = await mongodb.MongoClient.connect('mongodb://127.0.0.1:27017');
await client.db('mushroom').collection('items').insertOne(req.body);
res.end('Completed');
});
expressApp.get('/', (req, res) => {
response.setHeader('content-type', 'text/html');
fs.createReadStream('./index.html').pipe(response);
});
const server = http.createServer(expressApp);
server.listen(1337, () => {
console.log(`Started server on http://127.0.0.1:1337/`);
});
Make sure you have Mongo installed and running on your computer, then run the code again. Now go back to Postman and change the body to use JSON with content like { "foo": "bar" }
. When you hit "send" you should see a response that says "Completed" and you should also find a new Mongo document in your Mongo database containing { "foo": "bar" }
. You can find this in Mongo with the steps below.
- Start your Mongo shell by running
mongo
in your terminal. - Switch to the "mushroom" database by running
use mushroom
in your Mongo shell. - Find your newly created Mongo document by running
db.collection('items').find({})
.
There you have it Mushrooms! You can now create servers and do some pretty awesome stuff using Node and JavaScript. Enjoy!