shu*_*mjr 0 javascript axios pug
我正在使用 axios CDN 链接,但它给出了此错误
Refused to load the script 'https://unpkg.com/axios/dist/axios.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
我正在使用哈巴狗模板引擎。这是我的 base.pug 代码:
doctype html
html
head
meta(charset='UTF-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title Natours |#{title}
link(rel='stylesheet' href='/css/style.css')
link(rel='shortcut icon' type='image/png' href='/img/favicon.png')
link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:300,300i,700')
body
//header
include _header
//content
block content
h1 this is a placeholder
//footer
include _footer
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
script(src='/js/login.js')
Run Code Online (Sandbox Code Playgroud)
这是我的login.js
const login=async (email,password)=>{
try{
console.log(email,password)
const res=await axios({
method:'POST',
url:'http://127.0.0.1:3000/api/v1/users/login',
data:{
email,
password
}
})
console.log(res);
}catch(err){
console.log(err.res)
}
}
document.querySelector('.form').addEventListener('submit',(e)=>{
e.preventDefault();
const email=document.getElementById('email').value;
const password=document.getElementById('password').value;
login(email,password)
})
Run Code Online (Sandbox Code Playgroud)
我也尝试过另一件事:
添加<meta>标签来修改CSP,但我无法修改'script-src',我不知道为什么。我想我只能对 CSP 添加更多限制以使其更安全,但出于安全考虑我无法放松它。
最后我回答我自己的问题。首先我们需要了解内容安全策略(CSP)。因此,请查看这里https://content-security-policy.com/。这里我使用头盔来设置一些标题。
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'", 'data:', 'blob:'],
fontSrc: ["'self'", 'https:', 'data:'],
scriptSrc: ["'self'", 'unsafe-inline'],
scriptSrc: ["'self'", 'https://*.cloudflare.com'],
scriptSrcElem: ["'self'",'https:', 'https://*.cloudflare.com'],
styleSrc: ["'self'", 'https:', 'unsafe-inline'],
connectSrc: ["'self'", 'data', 'https://*.cloudflare.com']
},
})
);
Run Code Online (Sandbox Code Playgroud)
一切都完成了。我应该告诉您的一件事是,请检查您的域您到底在使用什么,在我的情况下,我使用 127.0.0.1 并且我不断通过本地主机请求。因此,我设置的标头仅适用于 127.0.0.1,不适用于 localhost。最后一件事,如果您想使用“axios”,请通过“npm”而不是任何 CDN 使用。
| 归档时间: |
|
| 查看次数: |
2292 次 |
| 最近记录: |