LoginSignup
5
3

More than 5 years have passed since last update.

lite-server(Browsersync) - クロスドメイン制約を回避する

Posted at

開発時のシミュレーションでローカルに立てた別のサーバーにアクセスしてファイルをダウンロードするといったことを試すときに、手軽に実行したかったのでlite-serverとコマンドを打つだけでローカルサーバーになる、lite-serverBrowsersyncのラッパー)を使用した。

そこへXMLHttpRequestすると、'Access-Control-Allow-Origin'の指定がヘッダーにないよ~アクセス出来ないよ〜と言われてしまう。

XMLHttpRequest cannot load http://localhost:3000/honyarara.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3002' is therefore not allowed access.

Browsersyncのオプションとして、プロキシとしてたてる事でも回避できるけれど、別ドメインという想定で実装を行いたかったので、browsersyncでたててるサーバー側のヘッダにどこからでもアクセスしていいよ〜という設定を追加する。

// ヘッダを追加する
function setHeader(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    next();
}

module.exports = {
    server: {
        middleware: {
            0: setHeader
        }
    }
};

これでうまくアクセスできるようになりました。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3