Byg en Node.js API på under 30 minutter

Byg en Node.js API på under 30 minutter

Node.js kan være skræmmende for begyndere. Men dens fleksible struktur og mangel på strenge retningslinjer gør det mere kompliceret end det er.

Denne vejledning er en hurtig og enkel guide til Node.js, Express-rammen og MongoDB, der fokuserer på de grundlæggende REST-ruter og grundlæggende databaseinteraktion. Du bygger en simpel API-kedelplade, som derefter kan bruges som fundament for enhver app.

Hvem denne tutorial er til : Du skal have en grundlæggende forståelse af REST API'er og CRUD-operationer plus grundlæggende JavaScript-viden. Jeg bruger ES6 (hovedsagelig fedtpilfunktioner), men intet for komplekst.

Til denne vejledning opretter du skelettet til en back-end til en applikation til notering - tænk Google Keep. Du vil være i stand til at udføre alle fire CRUD-handlinger på dine noter: oprette, læse, opdatere og slette.

Sætte op

Hvis du ikke har Node installeret, se her.

I en ny mappe skal du køre npm init og følge med vejledningen og give din app navnet 'bemærkelsesværdig' (eller hvad du ellers måtte lide).

npm init

Når det er gjort, skal du have en package.json klar til at gå i din mappe. Dette betyder, at du kan begynde at installere de afhængigheder, du har brug for til dit projekt.

Du vil bruge Express som din ramme, MongoDB som database og en pakke kaldet body-parser til at hjælpe med at håndtere JSON-anmodninger.

npm install --save express [email protected] body-parser

Jeg anbefaler også stærkt at installere Nodemon som en dev-afhængighed. Det er en simpel lille pakke, der automatisk genstarter din server, når filer ændres.

Hvis du løber:

npm install --save-dev nodemon

Du kan derefter tilføje følgende script til package.json :

// package.json
 "scripts": { "dev": "nodemon server.js" },

Din komplette package.json skal se sådan ud:

// package.json
{ "name": "notable", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "dev": "nodemon server.js" }, "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.15.2", "express": "^4.14.0", "mongodb": "^2.2.16" }, "devDependencies": { "nodemon": "^1.11.0" }}

Nu kan du oprette din server.js- filog begynd at opbygge din API.

Vores server

Lad os starte med at kræve alle dine afhængigheder i server.js.

// server.js
const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');
const app = express();

Du skal bruge MongoClient til at interagere med din database. Bemærk, at du også initialiserer din app som en instans af Express, din ramme.

Den sidste ting, du skal gøre for at få din server til at køre, er at fortælle din app at begynde at lytte efter HTTP-anmodninger.

Du kan angive en port og starte lytningen sådan:

// server.js
const port = 8000;
app.listen(port, () => { console.log('We are live on ' + port);});

Hvis du nu kører npm run dev (eller node server.js hvis du ikke installerede Nodemon), skal du se 'Vi er live på port 8000' i terminalen.

Din server er live. Men det gør ikke meget. Eller noget, virkelig.

Lad os ordne det.

CRUDdy-ruter

I dette eksempel vil du bygge 4 ruter; at OPRETTE en note, LÆS dine noter, OPDATERE en note og SLETTE en note.

Dette giver dig en god idé om, hvordan du strukturerer næsten enhver grundlæggende rute med Node.

For at teste din API skal du dog efterligne en klientside, der fremsætter anmodninger. For at gøre det skal du bruge en fantastisk app kaldet Postman. Det giver dig mulighed for at lave enkle HTTP-anmodninger med tilpassede organer og parametre.

Installer Postman, og lad os begynde at opsætte dine ruter.

Super Organiseret

De fleste Node.js-tutorials (og mange rigtige apps) placerer alle deres ruter i en stor routes.js- fil. Dette gør mig lidt ubehagelig. I modsætning hertil fører opsplitning af dine filer i separate mapper til god læsbarhed og gør store apps mere håndterbare.

Du har ikke en stor app, men lad os gøre det rigtigt. Foretag følgende biblioteker: en app mappe med et ruter mappe inde i det, med en index.js og en note_routes.js fil inde i det.

Med andre ord: rod> app> ruter> index.js og note_routes.js.

mkdir appcd appmkdir routescd routestouch index.jstouch note_routes.js

Disse mapper kan virke som for store til din enkle lille app, men det er altid godt at starte med bedste praksis.

Din første rute

Lad os starte med C i CRUD- create. Hvordan ville du oprette en note?

Well, before you do that, you have to build a bit more infrastructure. In Express, routes are wrapped in a function, which takes the Express instance and a database as arguments.

Like this:

// routes/note_routes.js
module.exports = function(app, db) {
};

You can then export this function through your index.js:

// routes/index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) { noteRoutes(app, db); // Other route groups could go here, in the future};

Then import it for use in server.js:

// server.js
const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');
const app = express();
const port = 8000;
require('./app/routes')(app, {});app.listen(port, () => { console.log('We are live on ' + port);});

Note that since you don’t have a database yet set up, you’re just passing in an empty object.

Okay, now you can make your CREATE route.

The syntax is simple:

// note_routes.js
module.exports = function(app, db) { app.post('/notes', (req, res) => { // You'll create your note here. res.send('Hello') });};

When the app receives a post request to the ‘/notes’ path, it will execute the code inside the callback- passing in a request object (which contains the parameters or JSON of the request) and a response object (used to reply).

You can test this by using Postman to send a POST request to localhost:8000/notes.

Nice! You created your first real route.

Next step is to add some parameters to your request and process them in your API and, finally, add in your database.

Request Parameters

In Postman, go to the Body tab and add some key-value pairs, after selecting the x-www-form-urlencoded radio button.

This will add encoded form data to your request, which you’ll be able to process with your API.

Now in your note_routes.js, let’s just log out the body.

// note_routes.js
module.exports = function(app, db) { app.post('/notes', (req, res) => { console.log(req.body) res.send('Hello') });};

Try sending the Postman request and you’ll see… undefined.

Unfortunately, Express can’t process URL encoded forms on its own. But you did install that body-parser package…

// server.
const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app, {});app.listen(port, () => { console.log('We are live on ' + port);});

Now you should see the body as an object in the terminal.

{ title: 'My Note Title', body: 'What a great note.' }

Last step to your preliminary route: set up the database, and then add your data in.

The easiest way to set up a Mongo database is through mLab: it’s free for the smallest size, and quite fast to setup.

Once you create an account and a MongoDB deployment, add a user to the database with a username and password:

then grab the URL here (the second one):

And in a directory config in the root of your project, create a db.js file.

mkdir config cd configtouch db.js

Inside, add the URL:

module.exports = { url : YOUR URL HERE};

Don’t forget to add your username and password (the ones from the database user, not your mLab account) into the URL. (If you’re committing this project to Github, be sure to include a .gitignore file like so, so you don’t share your password with everyone.)

Now in your server.js, you can use the MongoClient to connect to your DB, and use this to wrap your app setup:

// server.js
const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => { if (err) return console.log(err) require('./app/routes')(app, database);
 app.listen(port, () => { console.log('We are live on ' + port); }); })

If you’re using the latest version of the MongoDB (3.0+), modify it like so:

// server.js
const express = require('express');const MongoClient = require('mongodb').MongoClient;const bodyParser = require('body-parser');const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => { if (err) return console.log(err) // Make sure you add the database name and not the collection name const database = database.db("note-api") require('./app/routes')(app, database);
 app.listen(port, () => { console.log('We are live on ' + port); }); })

(Thanks to Alex Stroulger for the fix for 3.0)

That’s the last of your infrastructure setup! It’s all route-building from here.

Adding to your Database

MongoDB stores data in collections- which are exactly how they sound. In your case, you want to store your notes in a collection called — you guessed it — notes.

Since you pass in your database as the db argument in your routes, you can then access it like so:

db.collection('notes')

Creating a note is as simple as calling insert on your collection:

const note = { text: req.body.body, title: req.body.title} db.collection('notes').insert(note, (err, results) => {}

Once the insert is complete (or has failed for whatever reason), you want to either send back an error or send back the newly created note object. Here’s the full note_routes.js:

// note_routes.js
module.exports = function(app, db) { const collection = app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); } }); });};

Try it out! Send an x-www-form-urlencoded POST request with Postman, with a title and body set under the Body tab.

The response should look like this:

If you log into mLab, you should also see the created note in the database.

Your READ Route

Now you can pick up the pace a bit.

Say you wanted to get back the note you just created, by navigating to localhost:8000/notes/{the id}. In this case, that would be localhost:8000/notes/585182bd42ac5b07a9755ea3.

(If you don’t have the ID for one of your notes, you can check on mLab or just create a new one).

Here’s what this would look like in note_routes.js:

// note_routes.js
module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { });
 app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); } }); });};

Just like before, you’re going to call a method on your database collection of notes. Here, it’s the aptly named findOne.

// note_routes.js
module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { const details = { '_id':  }; db.collection('notes').findOne(details, (err, item) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(item); } }); });
app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); } }); });};

You can grab the id from the URL parameters via req.params.id. However, if you try to just plop in the string into the above, it won’t work.

MongoDB requires not just an ID as a string, but as an ID object or, as they call it, an ObjectID.

Don’t worry, it’s an easy fix. Here’s the full code:

// note_routes.js
var ObjectID = require('mongodb').ObjectID;
module.exports = function(app, db) { app.get('/notes/:id', (req, res) => { const id = req.params.id; const details = { '_id': new ObjectID(id) }; db.collection('notes').findOne(details, (err, item) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(item); } }); });
app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); } }); });};

Try it out with one of your note ID’s, and it should look like this:

Your DELETE Route

Deleting an object is actually pretty much the same as finding an object. You just use the remove function instead of the findOne. Here’s the full code. I’ve highlighted what’s different from your GET:

// note_routes.js
// ...
 app.delete('/notes/:id', (req, res) => { const id = req.params.id; const details = { '_id': new ObjectID(id) }; db.collection('notes').remove(details, (err, item) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send('Note ' + id + ' deleted!'); } }); });
// ...

Your UPDATE Route

Last one! The PUT is basically a hybrid between READ and CREATE. You find the object, then update it accordingly. If you deleted your only note, time to make another one!

The code:

// note_routes.js
// ...
 app.put('/notes/:id', (req, res) => { const id = req.params.id; const details = { '_id': new ObjectID(id) }; const note = { text: req.body.body, title: req.body.title }; db.collection('notes').update(details, note, (err, result) => { if (err) { res.send({'error':'An error has occurred'}); } else { res.send(note); } }); });
// ...

Now you can update any of your notes, like so:

Note the imperfection with this code- if you fail to supply a body or title, the PUT request will nullify those fields on the note in the database.

You could easily add some conditional logic to update the fields only if they’re present in the request- I left that out just to keep it simple.

API Complete

That’s it! You have a working Node API with each of the four major CRUD operations.

The goal of this tutorial was to give you a degree of familiarity with Express, Node, and MongoDB — you can use your simple app as a launching pad for more complex projects.

I fremtiden skriver jeg selvstudier for at skabe mere enkle API'er på forskellige sprog og rammer. Tryk på følgeknappen, hvis du er interesseret!

Hvis denne tutorial var nogen hjælp for dig, skal du ramme det grønne hjerte nedenfor - det betyder meget. Du er også velkommen til at give mig en kommentar med feedback eller spørgsmål.

Tak for læsningen!