Using node.js as a simple web server

后端 未结 30 2570
感情败类
感情败类 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:27

    The fast way:

    var express = require('express');
    var app = express();
    app.use('/', express.static(__dirname + '/../public')); // ← adjust
    app.listen(3000, function() { console.log('listening'); });
    

    Your way:

    var http = require('http');
    var fs = require('fs');
    
    http.createServer(function (req, res) {
        console.dir(req.url);
    
        // will get you  '/' or 'index.html' or 'css/styles.css' ...
        // • you need to isolate extension
        // • have a small mimetype lookup array/object
        // • only there and then reading the file
        // •  delivering it after setting the right content type
    
        res.writeHead(200, {'Content-Type': 'text/html'});
    
        res.end('ok');
    }).listen(3001);
    

提交回复
热议问题