我是 node.js 的新手,想知道为什么它没有按计划工作。我用过,
res.end("Hello world")
过去在页面上显示“Hello World”。
现在,使用以下代码,似乎它正在监听同一地址,但我导航到那里,但它没有转到该页面!就像 express没有提供响应。我很困惑。
web.js
const http = require('http');
var express = require('express');
var app = express();
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
//res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
app.get('/', function(request, response) {
response.sendFile('index.html');
});
index.html(同一目录)
<html>
<header>
<title>
This is title
</title>
</header>
<body>
Hello world
</body>
</html>
控制台输出
Atom Runner: web.js
Server running at http://127.0.0.1:3000/
最佳答案
您实际上并没有使用express。您正在将路由附加到它,但您正在创建一个单独的服务器对象并让其监听。你应该有更多类似这样的东西:
const http = require('http');
var express = require('express');
var app = express();
const hostname = '127.0.0.1';
const port = 3000;
app.get('/', function(request, response){
response.sendFile('index.html');
});
// Have the actual express app listen, not server
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Express 的目的是包装涉及在 Node.js 中创建服务器的样板。快来看看快报Hello world example 。该示例甚至不需要 http
模块:
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
关于javascript - 服务器未发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46710425/