javascript - 服务器未发送响应

标签 javascript html node.js express

我是 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/

相关文章:

javascript - 嵌套 AJAX 调用和 $.when.apply 列表 - 延迟 promise 无法正常工作

php - 无法使后续的Xpath查询正常工作

javascript - Google Chart IE9 问题(未定义)

node.js - 如何在 Node.js 中同步处理回调?

javascript - 如何使用 Express.js 处理空 URL 参数

javascript - 如何将html显示为文本?

javascript - .js 代码的 RazorEngine 评估问题

css - 如何修复 iPhone 和 iPod 的移动样式表错误?

javascript - MongoError : E11000 duplicate key error collection: test. 用户索引:email1_1 dup key: { email1: null }

javascript - 多次替换字符串之间的字符串