nodejs/express include local js file

前端 未结 3 1143
无人共我
无人共我 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: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);
    

提交回复
热议问题