gpt4 book ai didi

javascript - Express Static 不提供文件服务

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

我知道其他人提出了有关此主题的问题,但我无法通过阅读答案找出我的问题。

我希望我的 Node.js 应用程序为我的文件提供服务,看起来该页面正在向正确的路径发出对 css 文件的请求,但它仍然无法正常工作。

HTML 正在向 http://localhost:3000/public/css/register.css 发出请求对于使用链接标记 <link rel="stylesheet" href="../public/css/register.css"> 的 css 文件

app.js

//Load modules
var express = require('express');
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var app = express();
var router = express.Router();
var fs = require('module');
var path = require('path');

//Load body-parser and other middleware
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname + '/public')));

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

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


//Run Server
app.listen(3000, function(){
console.log("Listening on Port 3000");
});

users.js

//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("mongodb://MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')

//Express Setup
var express = require('express');
var router = express.Router();
var app = express();

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


//Define Schema
var userSchema = new Schema({
name: String,
email: String,
password: String
});
var User = mongoose.model('User', userSchema);

//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})

router.post('/register', function(req, res) {
console.log('Post Request')
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
})
newUser.save();
res.redirect('/users/register');
})

//Exports
module.exports = router;

当前文件结构

/MAIN
/public
/css
register.css
/routes
users.js
/views
register.html
package.json

最佳答案

愚蠢的问题,我不得不将源代码设置为 <link rel="stylesheet" href="/css/register.css">而不是<link rel="stylesheet" href="../public/css/register.css">

关于javascript - Express Static 不提供文件服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37505751/

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