使用Node js创建服务器时出错



我在同一个文件夹(tut67(中创建了这个javascript文件index.html、about.html、contact.html、services.html,但它仍然为每个html文件提供错误。(我用的是MacBook Air(。

代码如下::

const http=require('http'(;const fs=require('fs'(;

const hostname='127.0.0.1';

const端口=3000;

const home=fs.readFileSync('index.html'(;

const about=fs.readFileSync('./about.html'(;

const-contact=fs.readFileSync('./contact.html'(;

const services=fs.readFileSync('./services.html'(;

const-server=http.createServer((req,res(=>{console.log(req.url(;

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(home);

});

server.listent(端口,主机名,((=>{console.log(Server running at http://${hostname}:${port}/(;});

错误如下::

internal/fs/utils.js:307投掷失误;^

错误:ENOENT:没有这样的文件或目录,打开"index.html">

at Object.openSync (fs.js:476:3)
at Object.readFileSync (fs.js:377:35)
at Object.<anonymous> (/Users/shouryasharma/Desktop/Web Dev/tut67/index.js:7:17)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {

错误号:-2,syscall:'open',代码:"ENOENT",路径:'index.html'}

Node不知道文件的确切位置,即使它们在同一目录中。假设这是您的目录结构:

tut67
| index.html
| about.html
| contact.html
| services.html
| app.js

这将是app.js:的内容

const http = require('http');
const fs = require('fs');
const path = require('path');
const hostname = '127.0.0.1';
const port = 3000;
const home = fs.readFileSync(path.join(__dirname, 'index.html')).toString();
// const about = fs.readFileSync(path.join(__dirname, 'about.html')).toString();
// const contact = fs.readFileSync(path.join(__dirname, 'contact.html')).toString();
// const services = fs.readFileSync(path.join(__dirname, 'services.html')).toString();
// create the http server
const server = http.createServer((req,res) => {
console.log(req.url);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(home);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

index.html的样本内容可以是:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html> 

这将呈现出index.html,并将请求url适当地记录到控制台。请记住,未使用的变量可以(也应该(注释掉。

我无法重现你的错误,你也可以这样实现你的目标。

const http = require('http'); const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const home = fs.readFileSync('index.html');

const server = http.createServer((req,res)=>{ console.log(req.url);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream('index.html').pipe(res)
;
});
server.listen(port, hostname, () => { console.log(`Server running at http:${hostname}:${port}`); });

请在html文件名之前输入文件夹名:

const home = fs.readFileSync('introbackend/home.html');

相关内容

最新更新