[英]Serve a node_module using Express
我試圖在我的SPA平均堆棧應用程序中為我的客戶端提供特定的節點模塊。 我的app結構如下:
-app /
--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;
然后在我的index.html文件中使用該路徑:
<head>
<script src="scripts/angular-simple-sidebar.min.js"></script>
</head>
但是我在Chrome控制台中獲得的是:
任何幫助都將不勝感激!
我也嘗試過,但它對我有用。
我加載了一個外部CSS文件。
這是我的代碼
index.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}`)
});
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>
CSS / style.css文件
h1{
color: red;
}
另外,嘗試從提供靜態文件中刪除“腳本”部分並運行。
index.js
// ***** THIS IS THE PROBLEM LINE *****
app.use( express.static(__dirname + '/node_modules/angular-simple-sidebar'));
的index.html
<head>
<script src="angular-simple-sidebar.min.js"></script>
</head>
如果以上操作無法運行,請提供更多詳細信息或通過Github共享代碼。
只需添加一個前導斜杠
<head>
<script src="/scripts/angular-simple-sidebar.min.js"></script>
</head>
我已經嘗試安裝相同的模塊,它適用於我的代碼。 我可以訪問這些文件..這是我的代碼
'use strict';
const express = require('express');
const app = express();
app.use('/scripts', express.static(__dirname + '/node_modules/angular-simple-sidebar'));
app.get('/' ,(req, res) => {
res.send("<script src='scripts/angular-simple-sidebar.min.js'/>");
});
我認為你的路線還有其他一些問題..你可以在app /文件夾中提供實際app()
函數正在運行的代碼嗎?如果需要更多時間來解決這個問題你可以移動靜態文件從node_modules
到你的public/
靜態文件夾,如果它們只是靜態內容並查看它是否有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.