解析 NodeJS/Express 中的相对路径



我有一个网络调用不同文件夹(主文件夹内外(中的多个脚本、图像、样式等:

文件树

- /
- website
- scripts
- data.js
- customJquery.js
- styles
- animate.css
index.html
main.css
back.jpg
- otherFunctions.js

索引.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,800,800i">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Faster+One">
<link rel="stylesheet" href="styles/animate.css">
<link rel="stylesheet" href="main.css">
</head>
<body>
<img class="fondo" src="back.jpg">
<div class="content">
<!-- stuff... -->
</div>
<script src='scripts/data.js'></script>
<script src='scripts/customJquery.js'></script>
<script src='../otherFunctions.js'></script> <!-- Here's the conflict... -->
</body>
</html>

所有路径路由正常,除了../otherFunctions.js.似乎 NodeJS/Express 跳过了相对部分..,只接收处理错误的/otherFunctions.js

这是我的服务器端:

索引.js

const express = require('express');
const https = require('https');
const fs = require('fs');
const app = express();
const config = require('./config');
var webId;
var options = {
key: fs.readFileSync(config.paths.certificate.key),
cert: fs.readFileSync(config.paths.certificate.crt),
requestCert: false,
rejectUnauthorized: false
};
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
res.setHeader("Access-Control-Allow-Headers", "Accept, Access-Control-Allow-Headers, Access-Control-Request-Headers, Access-Control-Request-Method, Authorization, Content-Type, Origin, X-Requested-With");
next();
});
app.get('/favicon.ico', function(req, res) {
res.status(404).send('No favicon found');
});
app.get('/:id', function(req, res, next) {
id = req.params.id;
if (id.search(/w+.[A-z]+$/g) < 0) {
webId = id;
res.sendFile('index.html', {root: config.paths.webs + id});
} else {
res.sendFile(id, {root: config.paths.webs});
}
});
app.get('/:folder/:file', function(req, res) {
let folder = req.params.folder;
let file = req.params.file;
res.sendFile(file, {root: config.paths.webs + webId + '/' + folder});
});

app.get('*', (request, response) => {
response.send('GET request not found: ' + request.url);
});

app.use((err, request, response, next) => {
response.status(500).send(err.message);
});
https.createServer(options, app).listen(443, function() {
console.clear();
console.log("NodeJS secure server started at port 443");
});

除非您有以这种方式提供静态文件的特定需求,否则我建议使用快速内置的静态文件服务。

关于使用"../otherFunctions.js'在你的HTML中,恐怕浏览器会尝试解析相对于HTML文件本身位置的路径,所以例如,如果HTML文件my.domain.com/foo/bar/index.html,浏览器会寻找my.domain.com/foo/otherFunctions.js。理想情况下,要提供给客户端的所有静态文件都应位于一个文件夹中,然后由express.static(...)调用使用。

相关内容

  • 没有找到相关文章

最新更新