How to include javascript on client side of node.js?

后端 未结 5 1340
南笙
南笙 2020-11-30 05:25

I\'m a beginner of node.js and javascript.

I want to include external javascript file in html code. Here is the html code, \"index.html\":



        
相关标签:
5条回答
  • 2020-11-30 05:41

    The problem is that nomatter what your browser requests, you return "index.html". So the browser loads your page and get's html. That html includes your script tag, and the browser goes asking node for the script-file. However, your handler is set up to ignore what the request is for, so it just returns the html once more.

    0 讨论(0)
  • 2020-11-30 05:48

    Your handler is hardcoded to always return the content of /index.html. You need to pay attention to the resource that is being requested and return the right one. (i.e. if the browser asks for simple.js then you need to give it simple.js instead of index.html).

    0 讨论(0)
  • 2020-11-30 05:56

    Here is a working code. There should be more cleaner simpler code, but this is very close to minimal.

    This code suppose your index.html and other files are under /client dir.

    Good luck.

    var fs = require('fs');
    var url = require("url");
    var path = require('path');
    var mime = require('mime');
    
    var log = console.log; 
    
    var handler = function (req, res)
    {
        var dir = "/client";
        var uri = url.parse(req.url).pathname;
        if (uri == "/")
        {
            uri = "index.html";
        }
        var filename = path.join(dir, uri);
        log(filename);
        log(mime.lookup(filename));
        fs.readFile(__dirname + filename,
            function (err, data)
            {
                if (err)
                {
                    res.writeHead(500);
                    return res.end('Error loading index.html');
                }
                log(data);
                log(filename + " has read");
                res.setHeader('content-type', mime.lookup(filename));
                res.writeHead(200);
                res.end(data);
            });
    }
    
    0 讨论(0)
  • 2020-11-30 05:57
    function contentType(ext) {
        var ct;
    
        switch (ext) {
        case '.html':
            ct = 'text/html';
            break;
        case '.css':
            ct = 'text/css';
            break;
        case '.js':
            ct = 'text/javascript';
            break;
        default:
            ct = 'text/plain';
            break;
        }
    
        return {'Content-Type': ct};
    }
    
    
    
        var PATH = 'C:/Users/DELL P26E/node_modules'
        var http = require("http");
        var fs = require('fs');
        var url = require("url");
        var path = require("path")
        var fileName = "D:/index.html";
    
        var server = http.createServer (function (request, response) {
    
    
    
    
            var dir = "D:/";
            var uri = url.parse(request.url).pathname;
            if (uri == "/")
            {
                uri = "index.html";
            }
            var filename = path.join(dir, uri);
    
    
    
            fs.readFile( filename,
                function (err, data)
                {
                    console.log(err)
                    if (err)
                    {
                        response.writeHead(500);
                        return response.end('Error loading index.html');
                    }
    
                    var ext = path.extname(filename)
                    response.setHeader('content-type',contentType(ext));
                    response.writeHead(200);
                    response.end(data);
                });
    
    
        }).listen(3000);
    
        console.log('Server running on 8124') ;
    
    0 讨论(0)
  • 2020-11-30 06:00

    Alxandr is right. I will try to clarify more his answer.

    It happens that you have to write a "router" for your requests. Below it is a simple way to get it working. If you look forward www.nodebeginner.org you will find a way of build a proper router.

    var fs = require("fs");
    var http = require("http");
    var url = require("url");
    
    http.createServer(function (request, response) {
    
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");
    
        response.writeHead(200);
    
        if(pathname == "/") {
            html = fs.readFileSync("index.html", "utf8");
            response.write(html);
        } else if (pathname == "/script.js") {
            script = fs.readFileSync("script.js", "utf8");
            response.write(script);
        }
    
    
        response.end();
    }).listen(8888);
    
    console.log("Listening to server on 8888...");
    
    0 讨论(0)
提交回复
热议问题