【问题标题】:fetch function not working in a js static filefetch 函数在 js 静态文件中不起作用
【发布时间】:2022-01-26 02:15:06
【问题描述】:

这是我的快速项目架构

public
-- js
---- script.js
views
-- index.ejs
app.js

当我将包含函数 fetch() 的 js 脚本直接放在 .ejs 文件中时,一切正常。

但是当我尝试将我的 js 脚本放入 script.js 静态文件时,我收到以下错误:

Access to fetch at 'http://api.themoviedb.org/3/person/%3C%=%20game.id_beg.id_tmdb;%20%%3E/movie_credits?api_key=16f8c447ca077fe65e29f403f18652b0&language=en-US' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我在ejs文件中调用js静态文件如下方式

<script src="/js/script.js"></script>

我在 app.js 中有以下几行

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); 

app.use(express.static(path.join(__dirname, 'public')));

这里是包含 fetch 函数的代码:

function fetchMovieCast(id, title) {

    id_stack.push([id, title]);

    let req = movie_req + id + "/credits?api_key=" + api_key + "&language=en-US";
    fetch(req)
    .then(res => res.json())
    .then(data => {

        showCast(data.cast, title);
    })
    .catch(err => console.log(err));
}

如何纠正我的提取错误?

感谢您的回答

【问题讨论】:

  • 请显示实际的fetch() 代码。理想情况下,在 ejs 文件中显示有效的版本,并在脚本文件中显示无效的版本。
  • 函数 fetchMovieCast(id, title) { id_stack.push([id, title]);让 req = movie_req + id + "/credits?api_key=" + api_key + "&language=en-US"; fetch(req) .then(res => res.json()) .then(data => { showCast(data.cast, title); }) .catch(err => console.log(err));两者的代码完全相同
  • 请使用您问题下方的“编辑”链接将代码添加到您的问题中。多行代码在 cmets 中不可读,您的问题应该独立存在,而无需阅读 cmets。
  • 正常情况下已经完成了,但是静态文件和ejs文件的代码是一样的
  • 嗯,在你的两个实现中一定有些不同,因为fetch() 是来自 HTML 文件本身的 <script> 标记还是来自引用的脚本文件并不重要。所以,有些事情并不像你想象的那样。您是否准确地比较了两个fetch() 请求,以确切了解这两种情况有什么不同?

标签: node.js express


【解决方案1】:

当我尝试解码您正在使用的 URL 时,我得到了这个:

http://api.themoviedb.org/3/person/<%= game.id_beg.id_tmdb; %>/movie_credits?api_key=xxxxxxx&language=en-US

这看起来不像一个合法的 URL。我认为您正在构建的 URL 有问题。看来您的 EJS 模板中有一些东西卡在了您试图用于构建 URL 的变量中(根据 URL 中的 &lt;%= 判断)。

并且,当您将其移出 EJS 文件时,该变量不会被 EJS 处理,因此模板内容留在变量中,然后您将其放入 URL 中,因此它是一个错误的 URL。您要么需要将此变量保留在 EJS 文件中,以便它可以由 EJS 正确构建,要么您需要重新考虑如何在单独的 Javascript 文件中生成此变量。

我不确定为什么会导致 CORS 错误,但您需要先修复 URL 生成,然后查看是否还有其他问题。

【讨论】:

    猜你喜欢
    • 2015-11-09
    • 2023-01-16
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2020-09-12
    • 2016-08-20
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多