這是我的快速專案架構
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 生成,然后查看是否還有任何遺留問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396771.html
