在本地主机上运行 Node JS 服务器

Сим*_*нов 2 javascript node.js server

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

const http = require('http');

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

我将这段代码放在 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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

AJ *_* X. 5

您想发送您的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);
Run Code Online (Sandbox Code Playgroud)

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