Loading basic HTML in Node.js

后端 未结 20 1278
暗喜
暗喜 2020-11-28 17:34

I\'m trying to find out how to load and render a basic HTML file so I don\'t have to write code like:

response.write(\'...

blahblahblah

...\
相关标签:
20条回答
  • 2020-11-28 18:19

    we can load the html document with connect frame work. I have placed my html document and the related images in the public folder of my project where the below code and node modules present.

    //server.js
    var http=require('http');
    var connect=require('connect');
    
    var app = connect()
      .use(connect.logger('dev'))
      .use(connect.static('public'))
      .use(function(req, res){
       res.end('hello world\n');
     })
    
    http.createServer(app).listen(3000);
    

    I have tried the readFile() method of fs, but it fails to load the images, that's why i have used the connect framework.

    0 讨论(0)
  • 2020-11-28 18:19

    https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

    Here is my simple demo codes for host static HTML files by using Express server!

    hope it helps for you!

    // simple express server for HTML pages!
    // ES6 style
    
    const express = require('express');
    const fs = require('fs');
    const hostname = '127.0.0.1';
    const port = 3000;
    const app = express();
    
    let cache = [];// Array is OK!
    cache[0] = fs.readFileSync( __dirname + '/index.html');
    cache[1] = fs.readFileSync( __dirname + '/views/testview.html');
    
    app.get('/', (req, res) => {
        res.setHeader('Content-Type', 'text/html');
        res.send( cache[0] );
    });
    
    app.get('/test', (req, res) => {
        res.setHeader('Content-Type', 'text/html');
        res.send( cache[1] );
    });
    
    app.listen(port, () => {
        console.log(`
            Server is running at http://${hostname}:${port}/ 
            Server hostname ${hostname} is listening on port ${port}!
        `);
    });

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