Some more code

This commit is contained in:
Arti Zirk 2017-06-07 12:44:51 +03:00
parent c658a1b4fa
commit b8f0f00bdf
2 changed files with 77 additions and 2 deletions

View File

@ -2,9 +2,11 @@
"name": "ng1",
"version": "1.0.0",
"scripts": {
"start": "json-server ./data/db.json --id _id --static ./ --routes data/routes.json"
"start": "nodemon server.js"
},
"devDependencies": {
"json-server": "^0.9.5"
"body-parser": "^1.17.1",
"express": "^4.15.2",
"nodemon": "^1.11.0"
}
}

73
ng1/server.js Normal file
View File

@ -0,0 +1,73 @@
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json()); // before request handlers
app.use(express.static('./'));
app.get('/api/contacts', getContacts);
app.get('/api/contacts/:id', getContact);
app.post('/api/contacts', addContact);
app.put('/api/contacts/:id', changeContact);
app.delete('/api/contacts/:id', deleteContact);
var contacts = [
{
"_id": 1,
"name": "Jack",
"phone": "123"
},
{
"_id": 2,
"name": "Jill",
"phone": "456"
},
{
"_id": 3,
"name": "Mary",
"phone": "789"
}
]
app.use(errorHandler); // after request handlers
app.listen(3000, () => console.log('Server is running on port 3000'));
function errorHandler(error, request, response, next) { // there must be 4 arguments
response.status(500).send('error: ' + error.toString());
}
function getContacts(req, resp) {
resp.set('Content-Type', 'application/json');
resp.json(contacts);
}
function getContact(req, resp) {
var id = req.params.id;
resp.set('Content-Type', 'application/json');
for (let contact of contacts) {
if (contact._id == id) {
resp.json(contact);
return;
}
}
resp.json("");
}
function addContact(req, resp) {
var task = request.body;
console.log(task);
}
function changeContact(req, resp) {
var task = request.body;
console.log(task);
}
function deleteContact(req, resp) {
var id = request.params.id;
}