Node JS 配置

14

我正在尝试配置我的Node.js以运行我的HTML代码。我还使用了Bootstrap和Express.js。当我运行Node.js时,它没有加载CSS。有人能帮我找出问题在哪里吗?这是Node.js代码片段。

var express = require("express");
var app     = express();
var path    = require("path");
app.get('/',function(req,res) {
    res.sendFile(__dirname + '/home.html')
})
app.use(express.static(__dirname + '/public'))
app.listen(3000);

console.log("Running at Port 3000");
当我直接加载HTML文件时,它可以正确加载CSS,但是当我使用Node.js加载它时,它会失败。可能是什么原因导致了这个问题?

你不应该在 app.get() 处理程序内部使用 app.use() 调用。请将其放在外面。 - Madara's Ghost
嗨,谢谢回复。我尝试了你建议的方法,但仍然遇到同样的问题。你能告诉我可能是什么问题吗? - Anil Samal
我已编辑了问题以反映我尝试过的内容,请问可能出了什么问题? - Anil Samal
@bloodyknuckles 当我们尝试直接加载CSS文件时,它会显示无法获取文件。可能是什么问题?无法获取/public/stylesheets/home.css。 - Anil Samal
谢谢回复。我正在使用localhost:3000/public/stylesheets/home.css。 - Anil Samal
显示剩余4条评论
3个回答

7
请检查您的目录结构是否正确,并确认已为Node.js授予了正确的权限,使其能够进入目录并读取文件。
如果您的目录结构如下:
/public
    /stylesheets
        home.css
home.html
server.js

你的 server.js 代码应该长成这样:

var express = require("express");
var app     = express();
var path    = require("path");
app.get('/',function(req,res) {
    res.sendFile(__dirname + '/home.html');
})
app.use(express.static(__dirname + '/public'));
app.listen('3000', function() { 
    console.log("Listening on port 3000"); 
});

当你运行以下代码时:
node ./server.js

请在浏览器中访问以下网址:

http://localhost:3000/stylesheets/home.css

这样您就可以得到返回的home.css文件。


1
app.listen('3000',function(){ console.log("listening at 3000"); }); - Aishwat Singh

3

在 Express JS 项目中配置数据库

/config
  /database.js
/server.js
/.env

const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);

server.listen(process.env.ServerPort, '0.0.0.0', () => {
  logger.info(`Express server listening on port ${process.env.ServerPort}`);
});

当你运行这个命令:

node server.js

数据库.js文件

const My = require('jm-ez-mysql');

// Init DB Connection
const connection = My.init({
  host: process.env.DBHOST,
  user: process.env.DBUSER,
  password: process.env.DBPASSWORD,
  database: process.env.DATABASE,
  dateStrings: true,
  charset: 'utf8mb4',
  timezone: 'utc',
  multipleStatements: true,
  connectTimeout: 100 * 60 * 1000,
  acquireTimeout: 100 * 60 * 1000,
  timeout: 100 * 60 * 1000,
});

module.exports = {
  connection,
};

2
在express js项目中,您可以像require一样放置静态文件。"Original Answer"的翻译是"最初的回答"。
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

请查看此链接,了解如何将静态文件与express js连接起来:最初的回答

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接