我的文件夹结构如下所示:已更新
/public
twitter.html
/styles
styles.css
/views
index.html
server.js
package.json
我有一个链接到 twitter.html 的 index.html。我在 .js 文件中使用 Express 和 Node.js,所以我这样链接:
<a href="/twitter">Twitter</a>
我不能使用 <a href="twitter.html">Twitter</a>
因为它不适用于 Express,它只会给我这个:https://imgur.com/a/DL9aM (在网络浏览器上)应该是这样的:https://imgur.com/a/lyHja (在本地主机上)
当我运行 localhost 时,一切都按预期运行,我单击指向 Twitter 的链接,它运行正常。我来自 http://localhost:3000/
至 http://localhost:3000/twitter
.
但是,当我在网络浏览器上打开 index.html 然后单击链接到 Twitter 时,它显示“找不到您的文件”。我来自 file:///Users/name/twitter/views/index.html
至 file:///twitter
.
当我将这些文件上传到 Web 服务器并单击 Twitter 链接时,它显示“未找到请求的 URL/twitter 在此服务器上未找到。”。我来自 http://mypage.com/myusername/views/index.html
至 http://mypage.com/twitter
.
知道我做错了什么,因为在本地主机上运行时一切正常吗?
我的 script.js 看起来像这样:已更新
const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
const path = require('path')
const app = express()
let db
MongoClient.connect('mongodb://someuser:somepassword@cluster0-shard-00-00-fquoc.mongodb.net:27017,cluster0-shard-00-01-fquoc.mongodb.net:27017,cluster0-shard-00-02-fquoc.mongodb.net:27017/twitter?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(3000, () => {
console.log('listening on 3000')
})
})
app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({extended: true}))
//app.use(express.static(path.join(__dirname, 'public')));
//app.use('/public', express.static(path.join(__dirname, 'public')))
app.get('/public/twitter', (req, res) => {
db.collection('tweets').find().toArray((err, result) => {
if (err) return console.log(err)
res.send('/public/twitter.html')
})
})
app.get('/', (req, res) => {
return res.render('index');
});
app.post('/tweets', (req, res) => {
db.collection('tweets').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/twitter')
})
})
最佳答案
如果您的 Twitter 页面位于/views 文件夹中,则相应地访问它。
<a href="/views/twitter.html> Twitter </a>
更新:现在您发布了路由代码,这是您的问题。 app.use(express.static(path.join(__dirname, 'public')));
https://expressjs.com/en/starter/static-files.html
app.use('/public', express.static(path.join(__dirname, 'public')))
去掉你的观点,把 twitter 页面放在一个公共(public)目录中,然后执行/public/twitter 就可以了
app.get('/public/twitter', (req, res) => {
db.collection('tweets').find().toArray((err, result) => {
if (err) return console.log(err)
res.sendFile( __dirname + "/public/" + "twitter.html" );
})
})
关于javascript - 链接到另一个 html 文件在本地主机上有效,但在我将其上传到服务器时却无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983326/