gpt4 book ai didi

javascript - Node.JS托管基本网页错误: ENOENT

转载 作者:太空宇宙 更新时间:2023-11-04 02:56:30 25 4
gpt4 key购买 nike

node.js 新手,正在遵循下面链接中的基本教程。 https://www.tutorialspoint.com/nodejs/nodejs_web_module.htm

var http = require('http');
var fs = require('fs');
var url = require('url');

// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;

// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");

// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else {
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});

// Write the content of the file to response body
response.write(data.toString());
}
// Send the response body
response.end();
});
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

创建了两个与帖子完全相同的文件:index.html 和 server.js。然后当我尝试运行它时

node server.js

没有显示错误消息,但是当我尝试在浏览器上访问该页面时,它无法连接,并且控制台中显示错误。

任何帮助将不胜感激。

Server running at http://127.0.0.1:8081/

Request for / received.

{ Error: ENOENT: no such file or directory, open '' errno: -2, code: 'ENOENT', syscall: 'open', path: '' }

最佳答案

在给定的代码中,您有:

// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");

// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {

因为路径是 /,所以 pathname.substr(1) 将导致空字符串。并且由于您没有没有名称的文件,因此 fs.readFile 找不到要读取的文件,从而导致 ENOENT 错误。

给定的代码不会自动将空字符串解释为 index.html

因此您必须在浏览器中使用http://127.0.0.1:8081/index.html。或者更改代码逻辑,将空字符串解释为 index.html

关于javascript - Node.JS托管基本网页错误: ENOENT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43760145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com