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)
求教我应该怎么解决它呢?我哪里做错了呀~~感谢您的回答。
You need to learn basic debugging methods...
Suppose you are visiting 127.0.0.1:6060/index.html, then your request.url is /index.html; then the filename is [//index.html], please ask If you read //index.html, how can you read it?
Even if you don’t add the extra / in your filename, you won’t be able to read /index.html! You should find a way to remove the slash and read index.html directly. Do you understand this? As for how to remove it, you can simply operate request.url, use slice and other functions to get the result after removing /, or you can use path and other library files to parse it.
In addition, even if you read it, this code cannot be rendered into the browser. The browser will treat the read file as text, which means it will display your html source code. If you want the browser to render HTML, you also need to specify content-type: text/html in the response header, because if you do not specify content-type, the default is text/plain, which is displayed directly as text.
Please use relative paths