使用PUG模板尝试AXIOS时遇到的问题 [英] Facing problem while trying axios with pug template

查看:25
本文介绍了使用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’,因为它违反了以下内容安全策略指令:&Quot;Script-src‘Self’&Quot;。请注意,没有显式设置‘script-src-elem’,因此使用‘script-src’作为后备。

(&Q;

)

推荐答案

您需要添加Content Security Policy headers for script-src以允许您的站点从其他域加载脚本,在本例中为cdnjs.cloudflare.com

您可以在Web服务器(如果您正在使用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

这篇关于使用PUG模板尝试AXIOS时遇到的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆