问题描述
我正在尝试将axios与pug模板一起使用,但遇到了问题。 这是我的代码: base.pug
doctype html
html
head
block head
Meta(charset='UTF-8')
Meta(name='viewport' content='width=device-width,initial-scale=1.0')
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')
title Natours | #{title}
body
// HEADER
include _header
// CONTENT
block content
h1 This is a placeholder heading
// FOOTER
include _footer
script(src='https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js')
script(src='/js/login.js')
和login.js
const login = async (email,password) => {
try {
const res = await axios({
method: 'POST',url: 'http:127.0.0.1:3000/api/v1/login',data: {
email,password
}
});
console.log(res);
} catch (err) {
console.log(err);
}
};
document.querySelector('.form').addEventListener('submit',e => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
login(email,password);
});
但是每次我尝试提交表单时,都会在console.log中收到此错误 ” 拒绝加载脚本'https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js',因为它违反了以下内容安全策略指令:“ script-src'self'” 。请注意,未明确设置“ script-src-elem”,因此将“ script-src”用作后备。 “
解决方法
您需要添加Content Security Policy headers for script-src,以允许您的站点从其他域(在本例中为cdnjs.cloudflare.com
)中加载脚本。
您可以在Web服务器(如果正在使用)中或在Node.js应用程序中进行此操作。
Content-Security-Policy: script-src <source>;
在Node / Express中,它类似于:
res.setHeader('Content-Security-Policy','script-src cdnjs.cloudflare.com');
之类的库。