nodejs/express include local js file

前端 未结 3 1136
无人共我
无人共我 2020-12-09 04:47

Here is my current folder structure

css
   app.css
js
  app.js
node-modules
index.html
node-server.js
package.json

The node-server is hosti

相关标签:
3条回答
  • 2020-12-09 05:28

    I got it to work by using this syntax

    app.use(express.static('public'));
    

    Copy the css and js files under the 'public' directory and then add the reference in the index.html file

    <link rel="stylesheet" href="/css/reset.css">
    
    0 讨论(0)
  • 2020-12-09 05:30

    As Tomasz Kasperek pointed out, you need to let Express know that you intend to host these files in a static directory. This is technically called defining static middleware.

    This should look something like:

    var express = require('express');
    var app = express();
    
    // first parameter is the mount point, second is the location in the file system
    app.use("/public", express.static(__dirname + "/public"));
    

    It's super simple and I suggest you go the route of making some sort of public folder, rather than bothering to make specific files and folders static.

    Then the files would simply be referenced like so from the root index.html:

    <link href="public/css/reset.css" rel="stylesheet" type="text/css">
    

    Hope this helps you!

    0 讨论(0)
  • 2020-12-09 05:34

    Reason Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.

    Solution(Manual):

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

    Better Solution:

    Directory Structure:

    public
     css
       app.css
     js
      app.js
     index.html
    

    CODE:

    var express = require('express'),
        path = require('path'),
        app = express();
    
    // Express Middleware for serving static files
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get('/', function(req, res) {
        res.redirect('index.html');
    });
    
    app.listen(8080);
    
    0 讨论(0)
提交回复
热议问题