Using node.js as a simple web server

后端 未结 30 2222
感情败类
感情败类 2020-11-22 02:54

I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same

30条回答
  •  时光说笑
    2020-11-22 03:24

    Express function sendFile does exactly what you need, and since you want web server functionality from node, express comes as natural choice and then serving static files becomes as easy as :

    res.sendFile('/path_to_your/index.html')
    

    read more here : https://expressjs.com/en/api.html#res.sendFile

    A small example with express web server for node:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    app.get('/', function(req, res) {
        res.sendFile(path.join(__dirname + '/index.html'));
    });
    
    app.listen(8080);
    

    run this, and navigate to http://localhost:8080

    To expand on this to allow you to serve static files like css and images, here's another example :

    var express = require('express');
    var app = express();
    var path = require('path');
    
    app.use(express.static(__dirname + '/css'));
    
    app.get('/', function(req, res) {
        res.sendFile(path.join(__dirname + '/index.html'));
    });
    
    app.listen(8080);
    

    so create a subfolder called css, put your static content in it, and it will be available to your index.html for easy reference like :

    
    

    Notice relative path in href!

    voila!

提交回复
热议问题