You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Express与Pug中为按钮onclick绑定函数时遭遇CSP错误的问题求助

在Express与Pug中为按钮onclick绑定函数时遭遇CSP错误的问题求助

我最近在用Express搭配Pug做项目时碰到个头疼的问题:想把一个自定义函数绑定到按钮的onclick事件上,但怎么都搞不定,还触发了内容安全策略(CSP)的错误。

具体场景是这样的:我在页面的后端控制器里定义了一个showPopup函数,打算把它作为局部变量传给Pug模板,然后赋值给按钮的onclick属性,实现点击按钮弹出表单的功能。

先贴一下相关代码:

serverController.js

exports.get_server = (req, res, next) => {
  Server.findById(req.params.id).populate("channels").exec((err, server) => {
    if(err) next(err);

    let showPopup = () => {
      let c = document.querySelector("form.container-popup#add-channel");
      c.hidden = false;
    }

    res.render("server-page", {
      server: server,
      user: res.locals.currentUser,
      showPopup: showPopup
    })
  })
};

channel-side-bar.pug

div.secondary-side-bar
  div This is the channel side bar
  for channel in server.channels
    a(href=`/server/${server._id}/channel/${channel._id}`) #{channel.name}
    br
  button.add-channel(type="button" onclick=showPopup) Add Channel
  //- 注释掉的这行会在页面加载时直接执行函数,不是我想要的效果
  //- - showPopup()

form.container-popup#add-channel(method="POST" action=createChannelURL hidden=true)
  .div Create Channel
    label(for="name") Channel Name
    input(type="text" name="name" placeholder="Enter channel name here...")
    label(for="private") Private Channel?
    input(type="checkbox" value="private" name="private")
    button(type="submit") Submit

script.
  //- 我也试过在这里用JS绑定事件,但同样没成功
  //- let addChannelButton = document.querySelector("button.add-channel")
  //- addChannelButton.onclick = showPopup;
  console.log("in pug script")

结果运行后直接弹出了CSP错误:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src-attr 'none'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

我还尝试过给onclick加引号的不同写法:

  • onclick="showPopup"
  • onclick="showPopup()"

但这些写法都没能解决问题,反而还是触发同样的错误。另外我也试过直接在Pug的script标签里用DOM方法绑定onclick,但代码好像根本没执行到那一步?

实在搞不懂哪里出问题了,有没有大佬能指点一下?

备注:内容来源于stack exchange,提问作者matchamochi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 08:44:11