当我启动 Express 应用程序时,浏览器给出以下错误:
Refused to load the script 'http://localhost:1337/main.js' because it violates
the following Content Security Policy directive: "script-src unsafe-eval".
Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
在我的index.js 文件中,我已经像这样设置了头盔:
// Set Content Security Policies
const scriptSources = ["'self'", "'unsafe-inline'", "'unsafe-eval'"];
const styleSources = ["'self'", "'unsafe-inline'"];
const connectSources = ["'self'"];
app.use(
helmet.contentSecurityPolicy({
defaultSrc: ["'self'"],
scriptSrc: scriptSources,
scriptSrcElem: scriptSources,
styleSrc: styleSources,
connectSrc: connectSources,
reportUri: '/report-violation',
reportOnly: false,
safari5: false
})
);
app.use(helmet({
contentSecurityPolicy: false,
}));
我的index.html正在加载到.js文件中,如下所示:
<script type="module" src="./main.js"></script>
这是我的 GitHub 存储库:https://github.com/jgonzales394/fsn.pw
这里是头盔维护员。发生这种情况是因为您的指令需要嵌套在
directives
属性下。
例如:
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: scriptSources,
// ...
},
})
)
好吧,我设法让它正常工作。头盔允许我这样设置我的 CSP:
app.use(
helmet.contentSecurityPolicy({
defaultSrc: ["'self'"],
scriptSrc: scriptSources,
scriptSrcElem: scriptSources,
styleSrc: styleSources,
connectSrc: connectSources,
reportUri: '/report-violation',
reportOnly: false,
safari5: false
})
);
所以我的 main.js 文件是一个 vue 应用程序,我之前是这样写的:
import * as Vue from './src/vue.esm-browser.js';
const App = Vue.createApp({
data() {
return {
slug,
url
}
},
methods: {
createUrl() {
console.log(this.slug, this.url);
}
}
}).mount('#app');
我重写了这样的代码:
import { createApp, ref } from './src/vue.esm-browser.js';
const slug = ref('');
const url = ref('');
createApp({
setup() {
const createUrl = () => {
console.log(slug.value, url.value);
};
return {
slug,
url,
createUrl
};
}
}).mount('#app');
并且在我的 html 文件中能够调用 createUrl 而无需调用它。
好吧,我也遇到了类似的问题。当我嵌套指令而不是报告时,这个问题就解决了
app.use(helmet({
contentSecurityPolicy: {
directives: {
"script-src":['self',"http://localhost:3000/"],
},
reportOnly:true
},
}))