javascript - Node Express 服务器 : How to serve HTML file properly (scripts and css included) ?(csp、相对路径和类似的东西)

标签 javascript node.js twitter-bootstrap content-security-policy

(我知道这个问题已经以多种形式被问过很多次,但我尝试了很多解决方案,但没有一个能按预期工作。所以也许适合我工作的解决方案会帮助我理解。)

这是 structure of my project .

这是 index.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./../node_modules/bootstrap/dist/css/bootstrap.min.css">

    <title>Document</title>
</head>
<body>
    <nav class="navbar navbar-default ">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Brand</a>
            </div>
        </div>
    </nav>

    <script src="../node_modules//bootstrap.min.js"></script>
    <script src="./../node_modules/jquery/dist/jquery.js"></script>
</body>
</html>

这是 server/app.js。我让 res.sendFile();故意清空。

//export used
var express = require('express'),
    url = require("url"),  
    path = require("path"),  
    fs = require("fs");

const _port = 3000
var app = express();

app.get('/', function(req, res){
    res.sendFile();
});

app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});

服务器目前的目的只是发送 index.html,即公共(public)文件夹中的上一层。当向“/”发出请求时。我不能做 IIIITT, 有几个原因:
-我尝试使用 Helm 来解决内容安全策略。
-我尝试使用静态中间件来做一些事情..
- 我尝试使用 path.join/resolve

那么有没有人能以某种方式解释如何使用 Bootstrap 脚本/CSS 发送这个 public/index.html 文件?

祝你有个愉快的一天


编辑:

这是新的 app.js,它呈现 index.html 感谢 express.static 但 Bootstrap css/脚本不呈现:

//export used
var express = require('express'),
    url = require("url"),  
    path = require("path"),  
    fs = require("fs");

const _port = 3000
var app = express();



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

app.get('/', function(req, res){
    res.sendFile('../public/index.html',{root: __dirname});
});
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});

最佳答案

您必须在定义应用之后和其他路由之前添加静态中间件,因为建议首先放置静态中间件

使用路径模块加入路径,因为它有助于避免问题 操作系统使用斜杠和反斜杠的方式不同。

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

通过这样做,您可以在公共(public)目录中提供所有静态文件,包括脚本和 css。

关于javascript - Node Express 服务器 : How to serve HTML file properly (scripts and css included) ?(csp、相对路径和类似的东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355801/

相关文章:

javascript - onclick 提交按钮不返回 javascript 函数 yii

javascript - jQuery CSS 定位 div 元素悬停(跨浏览器问题)

javascript - Node : Communication between two servers (net)

javascript - 达到 100% 已满时关闭 Bootstrap 进度条

javascript - Angularjs:如何 ng-repeat 具有也是数组的字段的对象数组?

node.js - Mongoose 错误 : You can not `mongoose.connect()` multiple times while connected

javascript - 有没有办法在 CronJobs 中获取毫秒数?

html - 使用过多的 colspan 的潜在缺点是什么?

html - 如何在 Bootstrap 中创建包含多列的导航栏下拉菜单?

Javascript THREEJS 和 GC