繁体   English   中英

nodejs/express 包含本地 js 文件

[英]nodejs/express include local js file

这是我当前的文件夹结构

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

节点服务器托管index.html ,但我不知道如何加载app.jsapp.css文件。

index.html加载它们:

<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>

这是错误消息:

Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server 
responded with a status of 404 (Not Found)

我知道我需要要求或加载模块或其他东西,只是不知道是什么。

谢谢

原因Node.Js 不自行提供静态内容,必须定义路由以通过 Node 提供静态内容。

解决方案(手动)

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);

更好的解决方案

目录结构:

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

代码:

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);

正如Tomasz Kasperek指出的那样,您需要让 Express 知道您打算将这些文件托管在静态目录中。 这在技术上称为定义静态中间件

这应该类似于:

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"));

这非常简单,我建议您采用创建某种public文件夹的方法,而不是费心将特定文件和文件夹设为静态。

然后文件将简单地从根index.html像这样被引用:

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

希望这对你有帮助!

我通过使用这种语法让它工作

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

复制'public'目录下的css和js文件,然后在index.html文件中添加引用

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

 //we are in ./utils/dbHelper.js, here we have some helper functions function connect() { // connect do db... } function closeConnection() { // close connection to DB... } //let's export this function to show them to the world outside module.exports = { connect(), closeConnection() }; // now we are in ./main.js and we want use helper functions from dbHelper.js const DbHelper = require('./utils/dbHelper'); // import all file and name it DbHelper DbHelper.connect(); // use function from './utils/dbHelper' using dot(.) // or we can import only chosen function(s) const { connect, closeConnection } = require('./utils/dbHelper'); connect(); // use function from class without dot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM