【问题标题】:How to change MIME type with script in ReactJS如何在 ReactJS 中使用脚本更改 MIME 类型
【发布时间】:2018-04-03 05:02:12
【问题描述】:

我正在尝试将外部脚本加载到我的 react 文件中,它说:拒绝从“whereMyScriptIs”执行脚本,因为它的 MIME 类型('text/html')不可执行,并且严格的 MIME 类型检查是已启用。

如何更改类型以使其成为文本/javascript?我已将代码放在包含脚本的下面。任何帮助,将不胜感激!

componentDidMount () {
const script = document.createElement("script");
script.src = "./live_w_locator.js";
script.async = true;
script.type = "text/javascript";
document.body.appendChild(script);

}

【问题讨论】:

  • 前几天我刚收到这个错误,我如何修复它进入 URL 并尝试加载脚本本身。加载脚本后,我更正了 src 路径,它工作正常

标签: javascript html reactjs


【解决方案1】:

您不应包含这样的外部 javascript 文件。相反,您可以简单地将 import './live_w_locator' 添加到文件顶部。

【讨论】:

  • @PushedCrayon 当您以这种方式导入它时,您需要在 Javascript 文件中有一个默认导出。所以在live_w_locator.js文件的最后,需要添加一个export default functionName
【解决方案2】:
  • text/javascript 已过时
  • application/javascript 是当前 JS 的官方 MIME 类型

您需要确保脚本类型为 application/javascript 而不是 script.type = "text/javascript"

componentDidMount () {
const script = document.createElement("script");
script.src = "./live_w_locator.js";
script.async = true;
script.type = "application/javascript"; // notice the change here
document.body.appendChild(script);

您可以在 Iana.org 上阅读有关媒体类型的更多信息

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 2011-03-14
    • 2016-09-08
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2012-04-27
    • 1970-01-01
    相关资源
    最近更新 更多