[英]How i can set cookie and json in server response and redirect to client url/ PassportJS NodeJS
[英]How do I set up a nodejs server that gives the client the correct file by checking the url?
我正在嘗試編寫節點js服務器,如果資源在文件系統中,則返回用戶請求的任何內容。
例如,如果請求URL是/index.html
,它將嘗試在根目錄中找到名為“index.html”的文件,並使用該文件的流進行響應。 如果請求是/myscript.js
,它會做同樣的事情,找到一個名為myscript.js
的文件並將其傳遞給響應。
這是我到目前為止:
var http = require("http");
var fs = require("fs");
var port = process.env.PORT || 3000;
http.createServer(function (request, response) {
if (request.method == "GET") {
console.log(request.url);
if (request.url == "/") { // if the url is "/", respond with the home page
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("index.html").pipe(response);
} else if (fs.existsSync("." + request.url)) {
response.writeHead(200/*, {"Content-Type": request.headers['content-type']}*/);
fs.createReadStream("." + request.url).pipe(response);
} else {
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
} else {
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
}).listen(port);
// Console will print the message
console.log('Server running at http://127.0.0.1:' + port +'/');
關於這段代碼我有一些不喜歡的事情:
fs
認為每當路徑以/
開頭時,文件就不存在,所以我必須添加一個.
在文件路徑之前。 見第10和第12行。這總是有效嗎? 我覺得這是解決這個問題的一個非常糟糕的伎倆。 解決你的兩個要點:
.
使用fs
因為fs
會查看系統的根目錄。 請記住,系統根目錄與服務器根目錄不同。 path.extname
然后使用switch
語句來設置內容類型。 下面的代碼來自我寫的關於如何使用Node而不是Express設置簡單靜態服務器的博客文章 :
let filePath = `.${request.url}`; // ./path/to/file.ext
let ext = path.extname(filePath); // .ext
let contentType = 'application/octet-stream'; // default content type
if(ext === '') {
filePath = './index.html'; // serve index.html
ext = '.html';
}
switch (ext) {
case '.html':
contentType = 'text/html';
break;
case '.css':
contentType = 'text/css';
break;
case 'js':
contentType = 'text/javascript';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.