搜尋

首頁  >  問答  >  主體

初学 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);

跟着视频学习的。。为啥就不能读取我要的文件呢?我先在文件夹中写入了一个 index.html,然后试着在 localhost:6060/index.html 中读取文件并渲染到浏览器中,但是抛出错误了。

Error: cannot read this file
    at ReadFileContext.fs.readFile [as callback] (E:\node_learn\06 - output to c
lient\server.js:10:13)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)

求教我应该怎么解决它呢?我哪里做错了呀~~感谢您的回答。

迷茫迷茫2875 天前485

全部回覆(2)我來回復

  • 怪我咯

    怪我咯2017-04-17 16:16:02

    要學會基本的調試方法啊…
    假設你訪問的是127.0.0.1:6060/index.html,那麼你的request.url 就是/index.html;那麼filename就是【//index.html】,請問你去讀//index.html,怎麼可能唸出來呢?

    即便你的filename加上多餘的/,你去讀/index.html,也是讀不出來的啊!你應該想辦法把斜槓去掉,直接去讀index.html ,說這裡你明白了嗎。至於說你怎麼去掉,你可以簡單除暴的操作request.url,用slice等函數獲得去掉/之後的結果,也可以用path等函式庫檔案解析,均可。

    另外,即使你讀出來了,這一段程式碼也不可能渲染到瀏覽器中,瀏覽器會把讀到的文件當作文本,也就是會把你的html源碼顯示出來。想要瀏覽器渲染html,還要在回應的header中指定content-type:text/html,因為你不指定content-type的話,預設就是text/plain,也就是直接當做文字顯示。

    回覆
    0
  • 黄舟

    黄舟2017-04-17 16:16:02

    請使用相對路徑

    回覆
    0
  • 取消回覆