这是我的快速项目架构
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/<%= game.id_beg.id_tmdb; %>/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));
}
如何更正我的提取错误?
谢谢您的回答
uj5u.com热心网友回复:
当我尝试译码您使用的 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 中的 判断<%=
)。
而且,当您将其移出 EJS 档案时,该变量不会被 EJS 处理,因此模板内容留在变量中,然后您将其放入 URL 中,因此它是一个错误的 URL。您要么需要将此变量保留在 EJS 档案中,以便 EJS 正确构建它,要么需要重新考虑如何在单独的 Javascript 档案中生成此变量。
我不确定为什么会导致 CORS 错误,但您需要先修复 URL 生成,然后查看是否还有任何遗留问题。
0 评论