Running Node JS server on localhost

本小妞迷上赌 提交于 2019-12-02 10:49:53

问题


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);

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>

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

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

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.


回答1:


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);

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.



来源:https://stackoverflow.com/questions/46141175/running-node-js-server-on-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!