【问题标题】:Running Node JS server on localhost在 localhost 上运行 Node JS 服务器
【发布时间】:2018-02-18 20:06:40
【问题描述】:

例如,我想制作一个非常简单的 Web 服务器。

const http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    res.write("Hello!");
    res.end();
}).listen(8080);

我将此代码放入 WebStorm 并运行它。然后我放到同目录下的index.html文件。

<body>
    <button id="btn">Click Me</button>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <script src="requester.js"></script>
</body>

我也将 requester.js 文件放在同一个文件夹中。

$('#btn').on("click", function () {
    $.get('/', function () {
        console.log('Successful.');
    });
});

然后我在所有文件所在的文件夹中执行命令 live-server。我不知道如何使服务器在本地主机上工作。提前谢谢你。

【问题讨论】:

  • 您没有表现出将文件实际发送给用户的任何努力。看看expressjs.com,尤其是他们的 .static 方法...
  • 我只需要对 http 模块执行此操作。有可能吗?
  • 是的。看看 .sendFile、fs.readFile、Streams。

标签: javascript node.js server


【解决方案1】:

您想发送index.html 文件而不是字符串“Hello”:

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

http.createServer(function (req, res) {
    //NOTE: This assumes your index.html file is in the 
    // .    same location as your root application.
    const filePath = path.join(__dirname, 'index.html');
    const stat = fs.statSync(filePath);

    res.writeHead(200, {
        'Content-Type': 'text/html',
        'Content-Length': stat.size
    });

    var stream = fs.createReadStream(filePath);
    stream.pipe(res);
}).listen(8080);

根据您未来服务器的复杂性,您可能需要研究 express 作为内置 http 模块的替代方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2014-10-11
    • 2014-10-13
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多