如何解决如何正确设置helmet.js来解决CSP问题?
当我启动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'"],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而无需调用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。