我試圖創建一個簡單的快速應用程序,但它在控制檯中運行。當我在我的瀏覽器中打localhost:3000時,我收到網絡錯誤。我似乎不知道問題是什麼。我試圖創建一個簡單的快速應用程序,但它似乎不工作
這是我的代碼。
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use (function (req, res, next) {
console.log (req.headers);
res.writeHead (200, {'Content-Type': 'text/html'});
res.end ('<html><body><h1>Hello world</h1></body></html>');
});
// listing for request at port: 7000 no http.createServer needed
app.listen (console.log (
`Success server running at http://${hostname}: ${port}`
));
但是,當我在純節點創建一個類似的應用程序,它工作正常。
這裏是我的代碼:
var fs = require('fs');
var path = require ('path');
var http = require ('http');
var hostname = 'localhost';
var port = 3000;
var server = http.createServer (function (req, res) {
console.log ('request for ' + req.url + ' using ' + req.method + ' method');
// checking if the request method is Get
if (req.method == 'GET') {
var fileUrl;
// checking for the request url if it is the home page or not and storing the correct request url in fileUrl variable
if (req.url == '/') fileUrl = '/index.html';
else fileUrl = req.url;
var filePath = path.resolve ('./public'+fileUrl);
var fileExt = path.extname (filePath);
if (fileExt == '.html' && req.url !== '/favicon.ico') {
fs.exists (filePath, function (exists) {
if (!exists) {
res.writeHead (404, {'content-type': 'text/html'});
res.end ('<h1> The file </h1>' + fileUrl + '<h1>is not found. Make sure your browser input is correct and try again!</h1>');
console.log('hello no favicon found');
return;
}
});
}
res.writeHead (200, {'content-type': 'text/html'});
fs.createReadStream (filePath).pipe(res);
} else {
res.writeHead (404, {'content-type': 'text/html'});
res.end ('<h1> The file' + fileUrl + 'not an html file');
console.log (fileUrl);
}
});
server.listen (port, hostname, function(){
console.log (`server started ${hostname}:${port}. Helloooooo`);
});
感謝您的評論和響應!
您將*錯誤*? - >顯示他們!而你對'app.listen'的調用完全沒有意義,你可以執行'app.listen(port,err => console.log(err))' –
我檢查了你的代碼。你錯過了要求在第一部分的代碼除了一切工作正常。 – kgangadhar