homework/ng1/server.js

74 lines
1.5 KiB
JavaScript

'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;
}