LoginSignup
125
110

More than 3 years have passed since last update.

Vue.jsとAPIサーバとのaxiosでCORSに引っかかった時のProxyを使った回避方法

Last updated at Posted at 2019-08-06

最初に

開発環境にて
Vue.jsでバックエンドのAPIをaxiosで叩こうとした時、
Policyで引っかかってしまうことがあります。

Access to XMLHttpRequest at 'http://localhost:3000/api/test' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

問題点

Originが違うため、ブラウザでアクセスが拒否されます。

(example)Originが違う
Vue.js:http://localhost:8080
Golang:http://localhost:3000

解決方法

  1. CORSを設定する
    CORSについて
    サーバ側で、Originを許可する必要があります。

  2. proxyを使って、回避します。

今回は2.のPROXYを使った解決方法をご紹介します。
2.のメリット
- ドメインをよしなに設定できるため、向き先を自由に変更できます
- axios.get('/api').then() のように、ドメインを指定する必要がないので、開発環境でも本番環境でもコード修正の必要がありません。
- 本番環境(Build)には影響しません

Proxyを使う

(example)Originが違う
Vue.js:http://localhost:8080
Golang:http://localhost:3000

の場合、

Vue.js側のroot階層で
vue.config.jsを作成します

vue.config.js
module.exports = {
  devServer: {
    proxy: {
      "/api/": {
        target: "http://localhost:3000",
      }
    }
  }
};

このように書いておくと、

axios.get("/api/test").then(res=>{
    console.log(res.data)
})

Golang側の/api/**にアクセスする時、向き先をhttp://localhost:3000に変更します。

これで、policyを回避できます。

おまけ

こんな感じで書いておくと、env設定で向き先を自由に変更ことができます!

module.exports = {
  devServer: {
    proxy: {
      "/api/": {
        target:  process.env.USE_LOCAL_SERVER ? 'http://localhost:3000' : 'http://aaa.com',
      }
    }
  }
};
125
110
1

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
125
110