使用 Express 提供 node_module

Kra*_*ang 2 node.js express

我正在尝试在我的 SPA 平均堆栈应用程序中为我的客户端提供一个特定的节点模块。我的应用程序结构如下:

-应用程序/

--index.html

-node_modules/

-index.js

我想通过在我的 index.js 文件中执行此操作,使模块 angular-simple-sidebar 在我的前端可用:

'use strict';
let express = require('express');
let routes = require('./api/routes');
let path = require('path');

app.use((req, res, next) => {
  req.start = Date.now();
  next();
});

// ***** THIS IS THE PROBLEM LINE *****
app.use('/scripts', express.static(__dirname + '/node_modules/angular-simple-sidebar'));


app.use(express.static(path.join(__dirname, './app')));
app.use(routes);

app.get('/', (req, res) => {
  res.sendFile('index.html', {
    root: ('./app')
  });
});

/* GET Api index page */
app.get('*', (req, res) => {
  res.send('404 page not found!', 404);
});

app.listen(3000, () => {
  console.log('Express server is listening on port 3000');
});

module.exports = app;
Run Code Online (Sandbox Code Playgroud)

然后在我的 index.html 文件中使用该路径:

<head>
<script src="scripts/angular-simple-sidebar.min.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

但是,我在 chrome 控制台中得到的只是:

铬控制台输出

任何帮助都将不胜感激!

小智 5

我试过同样的,但它对我有用。

我加载了一个外部 CSS 文件。

这是我的代码


索引.js

// Get the required modules
const express = require('express');


let path = require('path');

const port = process.env.PORT || 8080;

const host = 'localhost';

var app = express();


// For serving static assets

app.use(express.static(path.join(__dirname, '/public')));

app.use('/css', express.static(__dirname + '/css'));

app.get('/', (req, res) => {
  res.sendFile('index.html', {
    root: (__dirname + '/public')
  });
});

// Start Server
app.listen(port, function (){
    console.log(`Server running on http://${host}:${port}`)
});
Run Code Online (Sandbox Code Playgroud)

public/index.html(在你的情况下,这是 app/index.html)

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/style.css" rel="stylesheet">
    </head>
    <body>
    <h1>Hello World</h1>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

css/style.css

h1{
    color: red;
}
Run Code Online (Sandbox Code Playgroud)

此外,尝试从提供静态文件中删除“脚本”部分并运行。


索引.js

// ***** THIS IS THE PROBLEM LINE *****
app.use( express.static(__dirname + '/node_modules/angular-simple-sidebar'));
Run Code Online (Sandbox Code Playgroud)

索引.html

<head>
<script src="angular-simple-sidebar.min.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

如果以上无法运行,请提供更多详细信息或通过 Github 共享代码。