前提・実現したいこと
Node.js(Express)で外部apiから画像データを取得するアプリを作成しています。
img-srcにURLを設定したところCSPエラーが発生したので、CSPヘッダの内容を変更するか削除したいのですが、うまくいきません。
発生している問題・エラーメッセージ
エラーメッセージ
console
1Refused to load the image '<URL>' because it violates the following Content Security Policy directive: "img-src 'self' data:".
設定されているCSPヘッダ
header
1Content-Security-Policy: default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
該当のソースコード
JavaScript
1const express = require('express'); 2const router = express.Router(); 3const request = require('request'); 4 5const apiKey = 'hogehoge'; 6const apiBaseUrl = 'http://api.themoviedb.org/3'; 7const nowPlayingUrl = `${apiBaseUrl}/movie/now_playing?api_key=${apiKey}`; 8const imageBaseUrl = 'https://image.tmdb.org/t/p/w500/'; 9 10router.use((req, res, next) => { 11 res.locals.imageBaseUrl = imageBaseUrl; 12 next(); 13}); 14 15router.get('/', (req, res, next) => { 16 request.get(nowPlayingUrl, (error, response, movieData) => { 17 const parsedData = JSON.parse(movieData); 18 res.render('index', { 19 parsedData: parsedData.results 20 }); 21 console.log(parsedData); 22 }); 23}); 24 25module.exports = router; 26
ejs
1<% parsedData.forEach(movie => { %> 2 <div class="col-md-3 col-sm-4 poster"> 3 <img src="<%= imageBaseUrl + movie.poster_path %>" /> 4 </div> 5<% }); %>
JSONで取得した外部データをparsedData
という形でviewに渡し、ベースURLと画像データのパスを連結して画像を表示させるようにしています。
試したこと
htmlのmetaタグでCSPの設定を変更する。
html
1<meta http-equiv="Content-Security-Policy" content="img-src https://image.tmdb.org;">
CSPヘッダを無効化する
JavaScript
1app.disable('Content-Security-Policy');
CSPヘッダを削除する
JavaScript
1app.use(function(req, res, next) { 2 res.removeHeader('Content-Security-Policy'); 3 next(); 4});
いずれも反映されず、最初に示したCSPヘッダが返ってきました。
解決方法がわかる方いらっしゃいましたらご教授頂けると幸いです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。