Back-End
If you are using nvm
nvm use stable
Initialize a new Node project
The first step with node is to initialize a new project:
cd back-end
npm init
This will ask you a number of questions. Here is how I answered them:
package name: (node-express-vue-todo)
version: (1.0.0)
description: todo list
entry point: (script.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)
Be sure to make the entry point server.js
Now you need to install Express, which makes it easy to create a REST API, and body-parser, which makes it easy to parse incoming requests. This will automatically save these packages as dependencies in package.json:
npm install express body-parser
Setup
We'll start with a basic setup for a back end server. In server.js, put the following:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
// parse application/json
app.use(bodyParser.json());
app.listen(3000, () => console.log('Server listening on port 3000!'));
This is the boilerplate we'll use for a Node and Express back end. We first load the modules we need. Then we create an Express app and we configure the body parser library so that it will parse forms and JSON requests.
We start the server on port 3000.
REST API
Create Operation
app.post('/api/items', (req, res) => {
id = id + 1;
let item = {
id: id,
text: req.body.text,
completed: req.body.completed
};
items.push(item);
res.send(item);
});
We use post and the send send the created item with status 200.
Read Operation
app.get('/api/items', (req, res) => {
res.send(items);
});
Updating Items
app.put('/api/items/:id', (req, res) => {
let id = parseInt(req.params.id);
let itemsMap = items.map(item => {
return item.id;
});
let index = itemsMap.indexOf(id);
if (index === -1) {
res.status(404)
.send("Sorry, that item doesn't exist");
return;
}
let item = items[index];
item.text = req.body.text;
item.completed = req.body.completed;
res.send(item);
});
We use put for updating items and send it with status 200 (default)
Delete Items
app.delete('/api/items/:id', (req, res) => {
let id = parseInt(req.params.id);
let removeIndex = items.map(item => {
return item.id;
})
.indexOf(id);
if (removeIndex === -1) {
res.status(404)
.send("Sorry, that item doesn't exist");
return;
}
items.splice(removeIndex, 1);
res.sendStatus(200);
});
'Node.js' 카테고리의 다른 글
[Node.js] Make API Server (template: Pokemon) (0) | 2022.03.20 |
---|---|
[Node.js] Front End - Axios Library(Vue CLi) (0) | 2022.03.19 |
Node.js Stream & Buffers (0) | 2022.03.19 |
Node.js Basics (Read & Write & Create & Remove) (0) | 2022.03.19 |
Node.js Installation and Run it simply (0) | 2022.03.19 |