node.js - ExpressJS Helm cps 字体问题

标签 node.js express content-security-policy helmet.js

我添加了 Helm 功能来设置 CPS,但是字体存在问题。一个简单的例子如下:

但是,它会正确加载除它所提示的字体之外的所有资源。

示例.css

src: url("/assets/fonts/font.eot") 

Example.com

app.use(csp({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "'unsafe-inline'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        imgSrc: ["'self'"],
        fontSrc: ["'self'", "'unsafe-inline'"],
        sandbox: ['allow-forms', 'allow-scripts'],
        reportUri: '/report-violation',
        objectSrc: [],
    },
    reportOnly: false,
    setAllHeaders: false,
    disableAndroid: false,
    browserSniff: true
}));

在浏览器中它给了我这个字体的错误消息

Font from origin 'http://localhost:3000' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我是否缺少一些使字体在浏览器中工作的东西?

在 Express 中,我已确保公共(public)文件和 Assets 文件设置正确。 ( Assets 中的一切都工作正常)。

app.use("/assets", express.static(__dirname + "/assets"));
app.use("/public", express.static(__dirname + "/public"));

最佳答案

这是一个 CORS(跨源资源共享)问题,我的示例来自对 eot 文件末尾的查询,例如就像 font-awesome 的 css 一样因为 css 使用了

src: url(...)

而不是

src: local(...)

如果找不到查询字符串,例如?v=4.6.1,它确实这样做了,它将进行查询来找到它,从而解决 CORS 问题。

Some info来自 MDN 的 @font-face 专门指出了这个问题:

Web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction.

MDN CORS info这是从该文档链接的。

因此,要么使用 local 关键字,错误查询会默默失败,要么您可以使用 Manning website 中的类似内容通过 Express 打开 CORS。 :

app.use(function(req, res, next) { res.header("访问控制允许来源", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 下一个(); });

但是当您使用 CSP 时,您会想深入了解如何进一步锁定 CORS header ,我想?

关于node.js - ExpressJS Helm cps 字体问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538077/

相关文章:

javascript - Firefox WebExtension,独立的 HTML 覆盖

javascript - 如何使用 javascript 从网站下载时重命名文件?

Node.js 程序在 `finally {}` 之后不运行 `try {}` block 并以代码 0 退出

express - type-graphql 找不到模块 'class-validator' 异常

node.js - NodeJS Express - 下载文件的端点

javascript - Mongoose 如何填充引用文档

javascript - 将鼠标事件广播到使用node.js和socket.io连接的所有 Node

node.js - 错误 : Please install tedious package manually

node.js - 如何使用winston 日志为nodejs 应用程序添加抄写客户端

css - 使用 attr 设置与 CSP 一起使用的内联 css 变量