繁体   English   中英

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

[英]Running Node JS server on localhost

例如,我想制作一个非常简单的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。 我不知道如何使服务器在本地主机上工作。 先感谢您。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM