初學(xué) node.js,讀取本地html文件報錯
問題描述
const http = require(’http’);const fs = require(’fs’);const server = http.createServer((request, response) => { const fileName = ’/’ + request.url; console.log(fileName); fs.readFile(fileName, (error, data) => { if(error) { throw new Error(’cannot read this file’); } else { response.write(data); } response.end(); });});server.listen(6060);
跟著視頻學(xué)習(xí)的。。為啥就不能讀取我要的文件呢?我先在文件夾中寫入了一個 index.html,然后試著在 localhost:6060/index.html 中讀取文件并渲染到瀏覽器中,但是拋出錯誤了。
Error: cannot read this file at ReadFileContext.fs.readFile [as callback] (E:node_learn06 - output to clientserver.js:10:13) at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)
求教我應(yīng)該怎么解決它呢?我哪里做錯了呀~~感謝您的回答。
問題解答
回答1:要學(xué)會基本的調(diào)試方法啊……假設(shè)你訪問的是 127.0.0.1:6060/index.html,那么你的request.url 就是 /index.html;那么filename就是 【//index.html】,請問你去讀//index.html,怎么可能讀出來呢?
即便你的filename不加上多余的/,你去讀/index.html,也是讀不出來的啊!你應(yīng)該想辦法把斜杠去掉,直接去讀index.html ,說道這里你明白了嗎。至于說你怎么去掉,你可以簡單除暴的操作request.url,用slice等函數(shù)獲得去掉/之后的結(jié)果,也可以用path等庫文件解析,均可。
另外,即使你讀出來了,這一段代碼也不可能渲染到瀏覽器中,瀏覽器會把讀到的文件當(dāng)做文本,也就是會把你的html源碼顯示出來。要想瀏覽器渲染html,還需要在響應(yīng)的header中指定content-type:text/html,因為你不指定content-type的話,默認就是text/plain,也就是直接當(dāng)做文本顯示。
回答2:請使用相對路徑
