在本地主机上运行Node JS服务器 [英] Running Node JS server on localhost

查看:51
本文介绍了在本地主机上运行Node JS服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a very simple web server like this for example.

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文件中.

I put this code in WebStorm and ran it. Then I put in the same directory index.html file.

<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文件放在同一文件夹中.

I also put requester.js file in the same folder.

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

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

Then I execute command live-server in this folder where all files are. I don't know how to make the server to work on localhost. Thank you in advance.

推荐答案

您要发送 index.html 文件而不是字符串"Hello":

You want to send your index.html file instead of the string "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模块中.

Depending on the complexity of your server in the future, you may want to investigate express as an alternative to the built-in http module.

这篇关于在本地主机上运行Node JS服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆