【问题标题】:Browsersync causes "Refused to execute inline script ... " error in SPA, if route in not rootBrowsersync 在 SPA 中导致“拒绝执行内联脚本...”错误,如果路由不是 root
【发布时间】:2019-09-11 10:58:58
【问题描述】:

我的 Vue SPA 中出现以下错误:

Refused to execute inline script because it violates the following Content Security 
Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, 
a hash ('sha256-KpHv3zgivMSB4dPnfYfqMt2lBibsYvM36EdoBBAsfbM='), or a nonce ('nonce-...') 
is required to enable inline execution. Note also that 'script-src' was not explicitly set, 
so 'default-src' is used as a fallback.

这个错误是由Browsersync引起的:

首先,仅当浏览器已由非根路由中的 browsersync 重新加载时才会发生此错误。比如这个错误发生在http://localhost:3001/sign-in,但是从来没有发生在http://localhost:3001

接下来,这个错误只发生在 SPA 中,而不会发生在普通网站中(多个页面,没有对 HTML5 历史的操作)。所以,我想,vue-router 参与其中。

【问题讨论】:

    标签: vue.js single-page-application vue-router browser-sync


    【解决方案1】:

    我对原因的假设是 BrowserSync 是错误的。原因是我过去不理解前端路由是如何工作的。让我们看看 vue-routerhistory mode 发生了什么:

    1. 构建完成后,将打开浏览器中带有路由“/”的新选项卡。
    2. Vue-router 生成的路由包括/sign-in
    3. 当我们转到非根页面时,例如。 G。到http://localhost:3000/sign-in
    4. 如果我们在代码中进行更正,项目将重新构建。
    5. 浏览器同步将重新加载页面http://localhost:3000/sign-in。但是 Browser Sync 不知道他必须为http://localhost:3000/sign-in 路由返回什么!它是静态服务器,它只知道http://localhost:3000/,并且可以返回相对于http://localhost:3000 的目录的文件。没有文件sign-in,所以会报错。

    sign-in这样的路由是由vue-router在路由初始化期间在http://localhost:3000/页面中创建的,但是在下次重新加载浏览器时这些数据会丢失。

    解决方案

    我确信存在超过 10 种方法(用于各种项目构建工具),但我对本地开发模式的哈希模式感到满意。要在生产和/或测试模式下启用历史模式,appropriate server setup required。很可能可以将浏览器同步设置为重定向,例如 http://localhost:3000/sign_in => http://localhost:3000/

    我不使用create-vue-app 之类的工具,但我认为 Webpack 预先设置了某种方式以避免上述问题 (Webpack hot module replacement?)。

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2014-07-14
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2018-02-25
      • 1970-01-01
      相关资源
      最近更新 更多