Running Node JS server on localhost

后端 未结 1 1167
粉色の甜心
粉色の甜心 2021-01-15 14:54

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         


        
相关标签:
1条回答
  • 2021-01-15 15:41

    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.

    0 讨论(0)
提交回复
热议问题