我在 Web 开发方面相当陌生,并且在我的 Express 应用程序中需要某些 Node 模块时遇到了问题。我需要访问某些代码,但我对 Node 的复杂性感到困难,而且我一生都无法访问我需要的 node_modules 。
我试图做的是利用我安装的node_modules 中的Cloudinary 视频播放器。我已在由 htmlRoutes.js 提供的 index.html 文件中包含路径链接,并且已明确指示 express 在文档中静态加载这些文件,但应用程序无法将这些路径识别为有效。我尝试过要求这些模块位于公共(public)文件夹中提供的单独的 JS 文件中,但这也是无效的。据我了解,这可能是我自己对客户端与服务器端编程的混淆,但我不知道如何解决这个问题,也不知道我应该阅读哪些资源才能做到这一点。
如有任何帮助,我们将不胜感激。这是我的服务器的样子:
const express = require("express");
const path = require('path');
const bodyParser = require('body-parser');
const baguetteBox = require('baguettebox.js');
const cloudinary = require('cloudinary');
const axios = require("axios");
const app = express();
// Define a port to listen for incoming requests
// Sets an initial port. We"ll use this later in our listener
const PORT = process.env.PORT || 8181;
app.use(express.static('public'));
//static routes that attempts to fetch scripts from node_modules without revealing inner directory structure
app.use(express.static(__dirname + '/node_modules/lodash'));
app.use(express.static(__dirname + '/node_modules/cloudinary'));
app.use(express.static(__dirname + '/node_modules/cloudinary-core'));
app.use(express.static(__dirname + '/node_modules/cloudinary-video-player'));
// Sets up the Express app to handle data parsing
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//routes
require("./routes/htmlRoutes.js")(app);
// require("./routes/apiRoutes.js")(app);
//configure cloudinary api calls
// cloudinary.config({
// cloud_name: 'name',
// api_key: 'key',
// api_secret: 'secret',
// secure: true
// })
// Start our server so that it can begin listening to client requests.
app.listen(PORT, function() {
// Log (server-side) when our server has started
console.log("App listening on: http://localhost:" + PORT);
});
最佳答案
我从未见过node_modules包直接用作静态文件,话虽如此,我对这种工作方式持不可知论。
处理此问题的另一种方法是使用 Webpack 等 bundler 并通过 Express.js 提供服务
这样做的原因是,即使是 JavaScript,Webpack 也会将代码编译成浏览器可解释的内容,而在很多情况下,您在 Node.js 包中找不到这些内容
关于node.js - 静态提供 JS 文件,包括使用 Express 的 Node 应用程序中的 Node 模块,以及客户端与服务器端编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52684829/