https://tw.alphacamp.co/blog/node-js-and-javascript
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
https://jsonplaceholder.typicode.com/
Put TODO list's codes into Node Server:
https://stackoverflow.com/questions/38757235/express-how-to-send-html-together-with-css-using-sendfile
https://pala.tw/frontend-backend-basic/
https://tecky.io/en/blog/Backend較Frontend難嗎/
https://progressbar.tw/posts/305
https://yakimhsu.com/project/project_w4_Network_http.html
In server.js
:
app.route("/method")
.get((req, res) => {
res.send("method get");
})
.post((req, res) => {
res.send("method post");
})
.put((req, res) => {
res.send("method put");
})
.delete((req, res) => {
res.send("method delete");
});
app.listen(3000);
Postman:
GET
:
POST
:PUT
:DELETE
:OPTIONS
: show methodsHere is the tree structure in class03_NodeJS/example-server/static
:
static
├── index.html
├── styles.css
├── todo.js
└── img
└── x.png
// using express static method
app.use(express.static("static"));
// using sendFile method
// cons: need to write the repeating method for every files
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/static/index.html"));
});
app.get("/styles.css", (req, res) => {
res.sendFile(path.join(__dirname, "/static/styles.css"));
});
app.get("/todo.js", (req, res) => {
res.sendFile(path.join(__dirname, "/static/todo.js"));
});
app.get("/img/x.png", (req, res) => {
res.sendFile(path.join(__dirname, "/static/img/x.png"));
});