【发布时间】: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()请求,以确切了解这两种情况有什么不同?