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!