前提・実現したいこと
'https://xxxx'のホストで'https://yyyy'からデータを取得する際にクロスオリジンの制約に引っかかってしまいます。ちなみにサーバー側はexpressを使っています。
corsが原因だとおもうのですが、解決の仕方がわかりません。
どなたかお分かりになられる方いらっしゃいましたらご教示お願いします。
発生している問題・エラーメッセージ
GET https://yyyy 499 Access to XMLHttpRequest at 'https://yyyy' from origin 'https://xxxx 'has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
該当のソースコード
サーバー側('https://yyyy')
var express = require('express'), app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()); var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }; app.use(allowCrossDomain); app.get('/api/test',function(req,res){ res.json({ message:"Hello,world" }); }); app.listen(80); console.log("server starting....");
index.html('https://xxxx')
window.onload = function () { var xhr = new XMLHttpRequest(); xhr.addEventListener('loadend', function () { if (xhr.status === 200) { console.log(xhr.response); } else { console.error(xhr.status + ' ' + xhr.statusText); } }); xhr.open('GET', 'https://yyyy'); xhr.send(null); };
試したこと
サーバー側のcorsのコードが問題かと思いほかにも試してみたのですが、うまくいきませんでした。
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
補足情報(FW/ツールのバージョンなど)
amazon linux cloud9 を使用しています。
あなたの回答
tips
プレビュー