Javascript 拒绝加载字体 'data:font/woff .....' 它违反了以下内容安全策略指令:“default-src 'self'”。请注意,'font-src'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45366744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:01:53  来源:igfitidea点击:

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

javascriptreactjswebpack

提问by JavaScript Learner

My react webApp give this Error in Browser Console

我的 react webApp 在浏览器控制台中给出了这个错误

Refused to load the font 'data:font/woff;base64,d09........' because it` 
`violates the following Content Security Policy directive: "default-src` `'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Also:

还:

Refused to connect to 'ws://localhost:3000/sockjs-node/782/oawzy1fx/websocket' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Screenshot of browser consoleenter image description here

浏览器控制台截图在此处输入图片说明

index.htmlHave this meta:

index.html有这个元:

<meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self' http://121.0.0:3000/">

WebPack.cofig.js

WebPack.cofig.js

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: path.join(__dirname, "./src"),
    devtool: debug ? "inline-sourcemap" : true,
    entry: "../src/index.js",

    module: {
        rules: [
            {
                test: /\.(jpe?g|png|gif|svg|woff|woff2|eot|ttf)$/i,  // a regular expression that catches .js files
                exclude: /node_modules/,
                loader: 'url-loader',
            },
            {
                test: /\.(js|.jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react','es2016', 'stage-0',],
                    plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
                }
            },
            {
                test: /\.css$/,
                use: [
                    "style-loader",
                    {
                        loader: "css-loader",
                    }
                ]
            }
        ]
    },
    resolve: {
        modules: [
            path.join(__dirname, "src"),
            "node_modules",
        ]
    },
    output: {
        path: __dirname + "/public/",
        // publicPath: "/public/",
        filename: "build.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
    devServer: {
        port: 3000, // most common port
        contentBase: './public',
        inline: true,
        historyApiFallback: true,
    }
};

回答by Subhashi

For me it was because of the Chrome extension 'Grammarly'. After disabling that, I did not get the error.

对我来说,这是因为 Chrome 扩展程序“语法”。禁用它后,我没有收到错误消息。

回答by nourish

To fix this specific error, CSP should include this:

要修复此特定错误,CSP 应包含以下内容:

font-src 'self' data:;

So, index.html meta should read:

所以, index.html 元应该是:

<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src 'self' data:; default-src 'self' http://121.0.0:3000/">

回答by IonicBurger

For what it's worth - I had a similar issue, assuming it's related to a Chrome update.

对于它的价值 - 我有一个类似的问题,假设它与 Chrome 更新有关。

I had to add font-src, and then specify the url because I was using a CDN

我必须添加 font-src,然后指定 url,因为我使用的是 CDN

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' data: fonts.gstatic.com;">

回答by brightmatter

From personal experience, it is always a best, first step to run your site in Incognito (Chrome), Private Browsing (Firefox), and InPrivate (IE11 && Edge) to remove the interference of add-ons/extensions. These can still interfere with testing in this mode if they are enabled explicitly in their settings. However, it is an easy first step to troubleshooting an issue.

根据个人经验,在隐身 (Chrome)、隐私浏览 (Firefox) 和 InPrivate (IE11 && Edge) 中运行您的网站以消除附加组件/扩展程序的干扰始终是最好的第一步。如果它们在其设置中明确启用,它们仍然会干扰在此模式下的测试。但是,这是解决问题的简单第一步。

The reason I am here, was due to Web of Trust (WoT) adding content to my page, and my page having had very strict Content Security Policy:

我在这里的原因是由于信任网络 (WoT) 向我的页面添加了内容,并且我的页面具有非常严格的内容安全策略:

Header set Content-Security-Policy "default-src 'none'; font-src 'self' data:; style-src 'self' 'unsafe-inline' data:; img-src 'self' data:; script-src 'self' 'unsafe-inline'; connect-src 'self';"

This caused many errors. I was looking more for an answer on how to tell the extension to not try and run on this site programatically. This way when people have extensions, they just won't run on my site. I imagine if this were possible, ad blockers would have been banned on sites long ago. So my research is a bit naive. Hope this helps anyone else trying to diagnose an issue that is not specifically tied to the handful of mentioned extensions in other answers.

这导致了许多错误。我正在寻找更多关于如何告诉扩展程序不要以编程方式尝试在此站点上运行的答案。这样当人们有扩展时,他们就不会在我的网站上运行。我想如果这是可能的,广告拦截器早就在网站上被禁止了。所以我的研究有点幼稚。希望这可以帮助其他任何人尝试诊断与其他答案中提到的少数扩展没有特别关联的问题。

回答by Ahmad Habony

You may need to add this to webpack.config.js:

您可能需要将此添加到webpack.config.js

devServer: {

        historyApiFallback: true
    }
};

回答by Sibeesh Venu

I was also facing the same error in my node application today.

我今天在我的节点应用程序中也遇到了同样的错误。

enter image description here

在此处输入图片说明

Below was my node API.

下面是我的节点 API。

app.get('azureTable', (req, res) => {
  const tableSvc = azure.createTableService(config.azureTableAccountName, config.azureTableAccountKey);
  const query = new azure.TableQuery().top(1).where('PartitionKey eq ?', config.azureTablePartitionKey);
  tableSvc.queryEntities(config.azureTableName, query, null, (error, result, response) => {
    if (error) { return; }
    res.send(result);
    console.log(result)
  });
});

The fix was very simple, I was missing a slash "/" before my API. So after changing the path from 'azureTable' to '/azureTable', the issue was resolved.

修复非常简单,我在 API 之前缺少一个斜杠“/”。因此,将路径从“azureTable”更改为“/azureTable”后,问题就解决了。

回答by Pramod

I had a similar issue. I had mentioned a wrong output folder path in angular.json

我有一个类似的问题。我在 angular.json 中提到了错误的输出文件夹路径

"outputPath": "dist/",

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

回答by Sventies

CSP helps you whitelisting sources that you trust. All other sources are not allowed access to. Read this Q&Acarefully, and then make sure that you whitelist the fonts, socket connections and other sources if you trust them.

CSP 可帮助您将您信任的来源列入白名单。不允许访问所有其他来源。仔细阅读此问答,然后确保将字体、套接字连接和其他来源(如果您信任的话)列入白名单。

If you know what you are doing, you can comment out the metatag to test, probably everything works. But realise that you / your user is being protected here, so keeping the metatag is probably a good thing.

如果您知道自己在做什么,则可以注释掉meta要测试的标签,可能一切正常。但是要意识到您/您的用户在这里受到保护,因此保留meta标签可能是一件好事。

回答by CriptoGirl

I had the same problem and which got resolved by using ./before the directory name in my node.jsapp, i.e.

我遇到了同样的问题,并通过./在我的node.js应用程序中的目录名称之前使用来解决,即

app.use(express.static('./public'));

app.use(express.static('./public'));

回答by Eshaan Kumar

I was facing similar issue.

我面临着类似的问题。

  1. You need to remove all the CSP parameter which are picked up by default and understand why each attribute is required.
  1. 您需要删除默认选择的所有 CSP 参数,并了解为什么需要每个属性。

font-src - is to tell the browser to load the font's from src which is specified after that. font-src: 'self' - this tells to load font family within the same origin or system. font-src: 'self' data: - this tells load font-family within the same origin and the calls made to get data:

font-src - 是告诉浏览器从之后指定的 src 加载字体。font-src: 'self' - 这告诉在同一来源或系统中加载字体系列。font-src: 'self' data: - 这告诉在同一个来源内加载字体系列以及为获取数据而进行的调用:

You might also get warning "** Failed to decode downloaded font, OTS parsing error: invalid version tag **" Add the following entry in CSP.

您可能还会收到警告“** 无法解码下载的字体,OTS 解析错误:版本标记无效 **” 在 CSP 中添加以下条目。

font-src: 'self' font

font-src: 'self' 字体

This should now load with no errors.

现在应该加载没有错误。