微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试使用Pug模板的axios时遇到问题

如何解决尝试使用Pug模板的axios时遇到问题

我正在尝试将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');

您还可以使用诸如https://www.npmjs.com/package/express-csp-header

之类的库。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。