【问题标题】:Facing problem while trying axios with pug template使用 pug 模板尝试 axios 时遇到问题
【发布时间】:2021-01-11 06:25:36
【问题描述】:

我正在尝试将 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' 用作后备。 "

【问题讨论】:

  • 我看到有人也在做 Udemy 的 Natours nodejs 课程;)

标签: node.js express axios pug


【解决方案1】:

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

您可以在您的网络服务器(如果您使用一个)或 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

【讨论】:

  • 非常感谢您的回复。我在节点方面有点新,喜欢做我的第一个节点并遇到了这个问题。所以你能告诉我一些细节,比如我应该在服务器的哪个位置使用“res. setHeader('Content-Security-Policy', 'script-src cdnjs.cloudflare.com');"?在您回答后,我在控制器中使用了它,但仍然面临同样的问题。比我安装 express-csp-header 但我收到此错误“SyntaxError: Identifier 'expressCspHeader' has been declared”。
  • 抱歉,我复制粘贴了两次“const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header');”所以得到了“SyntaxError: Identifier 'expressCspHeader' has been declared”错误。现在已修复,但我仍然收到错误,正如我在问题中提到的那样
  • 谢谢。使用“app.use(function(req, res, next) { res.setHeader( 'Content-Security-Policy', "script-src 'self' cdnjs.cloudflare .com" ); 返回下一个(); });"
猜你喜欢
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多