如果路由不是根目录,Browsersync 会导致 SPA 出现 "Refused to execute inline script ... " 错误
Browsersync causes "Refused to execute inline script ... " error in SPA, if route in not root
我在 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引起:
首先,只有当浏览器在非root 路由中被browsersync 重新加载时才会出现此错误。例如,此错误发生在 http://localhost:3001/sign-in
中,但从未发生在 http://localhost:3001
.
中
其次,此错误仅出现在 SPA 中,但不会出现在普通网站中(多页,无操作 HTML5 历史记录)。所以,我想,vue-router
参与其中。
我对原因的假设是 BrowserSync 错误。原因是我过去不理解前端路由是如何工作的。让我们看看 vue-router 的 history mode 中发生了什么:
- 构建完成后,浏览器中带有路由“/”的新选项卡将打开。
- Vue-router 生成的路由包括
/sign-in
.
- 当我们转到非根页面时,e。 G。至
http://localhost:3000/sign-in
- 如果我们在代码中进行更正,将重新构建项目。
- 浏览器同步将重新加载页面
http://localhost:3000/sign-in
。但是Browser Sync不知道他要return for http://localhost:3000/sign-in
什么路由!它是静态服务器,它只知道 http://localhost:3000/
并且可以 return 相对于 http://localhost:3000
目录的文件。没有文件sign-in
,所以会出错
像sign-in
这样的路由是vue-router
在路由初始化时在http://localhost:3000/
页面中创建的,但是下次浏览器重新加载时这些数据将丢失。
解决方案
我确信存在超过 10 种方法(针对各种项目构建工具),但我对本地开发模式上的哈希模式感到满意。要在生产 and/or 测试模式上启用历史模式,appropriate server setup required。很可能可以将浏览器同步设置为重定向,例如 http://localhost:3000/sign_in
=> http://localhost:3000/
.
我不使用像 create-vue-app
这样的工具,但我想 Webpack 以某种方式预先设置以避免上述问题(Webpack hot module replacement?)。
我在 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引起:
首先,只有当浏览器在非root 路由中被browsersync 重新加载时才会出现此错误。例如,此错误发生在 http://localhost:3001/sign-in
中,但从未发生在 http://localhost:3001
.
其次,此错误仅出现在 SPA 中,但不会出现在普通网站中(多页,无操作 HTML5 历史记录)。所以,我想,vue-router
参与其中。
我对原因的假设是 BrowserSync 错误。原因是我过去不理解前端路由是如何工作的。让我们看看 vue-router 的 history mode 中发生了什么:
- 构建完成后,浏览器中带有路由“/”的新选项卡将打开。
- Vue-router 生成的路由包括
/sign-in
. - 当我们转到非根页面时,e。 G。至
http://localhost:3000/sign-in
- 如果我们在代码中进行更正,将重新构建项目。
- 浏览器同步将重新加载页面
http://localhost:3000/sign-in
。但是Browser Sync不知道他要return forhttp://localhost:3000/sign-in
什么路由!它是静态服务器,它只知道http://localhost:3000/
并且可以 return 相对于http://localhost:3000
目录的文件。没有文件sign-in
,所以会出错
像sign-in
这样的路由是vue-router
在路由初始化时在http://localhost:3000/
页面中创建的,但是下次浏览器重新加载时这些数据将丢失。
解决方案
我确信存在超过 10 种方法(针对各种项目构建工具),但我对本地开发模式上的哈希模式感到满意。要在生产 and/or 测试模式上启用历史模式,appropriate server setup required。很可能可以将浏览器同步设置为重定向,例如 http://localhost:3000/sign_in
=> http://localhost:3000/
.
我不使用像 create-vue-app
这样的工具,但我想 Webpack 以某种方式预先设置以避免上述问题(Webpack hot module replacement?)。