在localhost上运行Node JS服务器

时间:2017-09-10 13:23:16

标签: javascript node.js server

我想制作一个非常简单的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。我不知道如何使服务器在localhost上工作。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您希望发送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模块的替代方案。

相关问题