Photo by Mohammad Rahmani on Unsplash
建立 http server
const http = require('http');
const path = require('path');
const fs = require('fs');
const fsPromises = require('fs').promises;
// PORT
const PORT = process.env.PORT || 3333;
// 建立 Server
const server = http.createServer((request, response) => {
console.log(request.url, request.method);
// 設定回應資料
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
let view_path = path.join(__dirname, 'view', 'index.html')
// 讀取樣板檔案
fs.readFile(view_path, 'utf8', (error, data) => {
response.end(data);
});
});
// 啟動 Server
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
變數說明
request 請求
變數 |
說明 |
request.url |
請求網址 |
request.method |
請求方法,GET、POST、PUT、DELETE |
request.headers |
標頭 |
request.headers.origin |
請求來源 |
request.body |
請求傳送的資料 |
request.cookies |
Cookie |
request.accepts() |
接受回傳什麼類型的資料 |
response 回應
變數 |
說明 |
response.statusCode |
HTTP 狀態碼,e.g. 404, 200 |
response.setHeader() |
設定標頭 |
response.end() |
結束請求,並寫入要回傳的資料 |
response.send() |
傳送資料 |
response.sendFile() |
傳送檔案 |
response.writeHead() |
寫入標頭 |
response.redirect() |
重新導向 |
response.status() |
設定狀態碼 |
response.json() |
回傳 JSON 格式資料 |
response.type() |
指定回傳格式類型 |
response.cookie() |
設定 Cookie |
response.sendStatus() |
傳送狀態 |
response.clearCookie() |
清除 Cookie |
response.cookie() 設定 Cookie
response.cookie("jwt", refreshToken, {
httpOnly: true, // JavaScript can not access
sameSite: 'None', // Strict, Lax, None,
secure : true, // https
maxAges: 24 * 60 * 60 * 1000, // expire time
});
參考資料
Donate KJ 贊助作者喝咖啡
如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!