gpt4 book ai didi

node.js - 在路由路径中搜索公共(public)文件夹

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:00 25 4
gpt4 key购买 nike

每当访问根目录之外的其他路由时,express 无法找到包含所有样式表和 javascript 文件的公共(public)文件夹,而是搜索路由路径内的资源。任何帮助将不胜感激。

错误访问 http://localhost:3000/users/login/给出-

GET/users/login/stylesheets/bootstrap.css 404 14.872 毫秒 - 10418
GET/users/login/stylesheets/style.css 404 7.134 毫秒 - 10418
获取/users/login/javascripts/bootstrap.js 404 57.890 毫秒 - 10418
获取/users/login/javascripts/bootstrap.js 404 5.326 毫秒 - 10418

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// extra modules
var hbs = require('hbs');
var defaultLogger = require('express-logger');

var index = require('./routes/index');
var users = require('./routes/users');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', {layout: './layouts/application'});
hbs.registerPartials(__dirname + '/views/layouts/partials');

app.use(express.static(path.join(__dirname, 'public')));
app.use(defaultLogger({path: "log/development.log"})); //logger
app.use(favicon(path.join(__dirname, 'public', 'bulb.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

使用.js

var express = require('express');
var router = express.Router();
var userService = require('../services/users')

/* GET users listing. */
router.get('/', function(req, res, next) {
userService.all(function(users){
res.render('users/dummy')
})
});

// GET login form
router.get('/login', function(req, res, next){
res.render('users/login', {title: 'Login'});
});

module.exports = router;

最佳答案

我猜你现在的路径格式如下:
<link href="stylesheets/bootstrap.css">

您应该始终包含 /在路径的起点。这将帮助您加载正确的路径。
<link href="/stylesheets/bootstrap.css">

关于node.js - 在路由路径中搜索公共(public)文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com