const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3001;
let server = http.createServer((request,response) => {
response.statusCode=200;
response.setHeader('content-Type','text/html');
if(url==='/index') {
fs.readFile(path.join(__dirname,'index.html'), 'utf8', (err,data) => {
if(err) throw err; response.end(data)
});
} else if(url==='/contact') {
fs.readFile(path.join(__dirname,'contact.html'), 'utf8', (err,data)=> {
if(err)throw err;response.end(data)
});
}
else if (url==='/about') {
fs.readFile(path.join(__dirname,'about.html'),'utf8',(err,data) => {
if (err) throw err;
response.end(data);
})
}
else if (url==='/profile') {
fs.readFile(path.join(__dirname,'profile.html'),'utf8', (err,data) => {
if (err) throw err;
response.end(data)
})
}
else if (url==='/service') {
fs.readFile(path.join(__dirname,'service.html'), 'utf8', (err,data) => {
if(err)throw err;
response.end(data)
})
}
});
server.listen(port,hostname, ()=> {
console.log(`serevr is started at http://${hostname}:${port}`)
});
http:此网址持续加载,但浏览器上没有显示网页
答案 0 :(得分:1)
您正在滥用url
模块。要访问当前路线,可以使用request.url
,并且setHeader
对象上没有request
方法
这是一个可行的例子
const http = require("http");
const fs = require("fs");
const path = require("path");
const hostname = "127.0.0.1";
const port = 3001;
let server = http.createServer((request, response) => {
if (request.url === "/index" || request.url === "/") {
fs.readFile(path.join(__dirname, "index.html"), "utf8", (err, data) => {
if (err) throw err;
response.writeHead(200, { "Content-Type": "text/html" });
response.end(data);
});
} else if (request.url === "/contact") {
fs.readFile(path.join(__dirname, "contact.html"), "utf8", (err, data) => {
if (err) throw err;
response.writeHead(200, { "Content-Type": "text/html" });
response.end(data);
response.end(data);
});
} else if (request.url === "/about") {
fs.readFile(path.join(__dirname, "about.html"), "utf8", (err, data) => {
if (err) throw err;
response.writeHead(200, { "Content-Type": "text/html" });
response.end(data);
response.end(data);
});
} else if (request.url === "/profile") {
fs.readFile(path.join(__dirname, "profile.html"), "utf8", (err, data) => {
if (err) throw err;
response.writeHead(200, { "Content-Type": "text/html" });
response.end(data);
response.end(data);
});
} else if (request.url === "/service") {
fs.readFile(path.join(__dirname, "service.html"), "utf8", (err, data) => {
if (err) throw err;
response.writeHead(200, { "Content-Type": "text/html" });
response.end(data);
response.end(data);
});
}
});
server.listen(port, hostname, () => {
console.log(`server is started at http://${hostname}:${port}`);
});