Skip to content

completed assignment task_list_server #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 43 additions & 25 deletions 09-node-express-server/task-list-http-server/server.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
const express = require('express')
const app = express()
const express = require("express");
const app = express();

/**
* Imagine there is a list of tasks like this:
* 1. Enroll to Scaler
app.use(express.json({ extended: true }));
/**
* Imagine there is a list of tasks like this:
* 1. Enroll to Scaler
* 2. Learn Node.js
* 3. Learn React.js
* 4. Get a job
* 5. Get a girlfriend/boyfriend
*
*
*/

/**
* When GET request is sent to 127.0.0.1:4114/tasks,
* response will be
* response will be
* [
* 'Enroll to Scaler',
* 'Learn Node.js',
Expand All @@ -22,41 +23,58 @@ const app = express()
* 'Get a girlfriend/boyfriend'
* ]
*/
app.get('/tasks', (req, res) => {

})
var taskList = {
1: "Enroll to Scaler",
2: "Learn Node.js",
3: "Learn React.js",
4: "Get a job",
5: "Get a girlfriend/boyfriend",
};
app.get("/tasks", (req, res) => {
res.send(Object.values(taskList));
});

/**
* If GET request is sent to 127.0.0.1:4114/tasks/1,
* Then response will be
*
* Then response will be
*
* 'Enroll to Scaler'
*
*
* If GET request is sent to 127.0.0.1:4114/tasks/2
* Then response will be
*
*
* 'Learn Node.js'
*/

app.get('/tasks/:id', (req, res) => {

// BONUS: figure out how `:id` part works
})
app.get("/tasks/:id", (req, res) => {
// BONUS: figure out how `:id` part works
if (req.params.id in taskList) {
res.send(taskList[req.params.id]);
} else {
res.send("Task not found");
}
});

/**
* When POST request is sent to 127.0.0.1:4114/tasks,
* with the body:
* { "task": "Complete NodeJS Assignment" }
*
* { "task": "Complete NodeJS Assignment" }
*
* Then a new task will be added to the list.
*
*
* 6. Complete NodeJS Assignment
*/

app.post('/tasks', (req, res) => {

})
app.post("/tasks", (req, res) => {
if (req.body.task == undefined) {
res.send("Please add a body to add a task. The format should be {\"task\": \"task name\"}");
} else {
taskList[Object.keys(taskList).length + 1] = req.body.task;
res.send("A new task " + req.body.task + " has been added to the list");
}
});

app.listen(4114, () => {
console.log('server started on http://127.0.0.1:4114')
})
console.log("server started on http://127.0.0.1:4114");
});