LoginSignup
16
20

More than 5 years have passed since last update.

axios で CORS によるクロスドメイン通信するとき

Last updated at Posted at 2018-07-05

コード

準備

import axios from "axios";
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

GET

let getApi = (path, params, headers) => {
    if (!params) {
        params = {};
    }
    if (!headers) {
        headers = {};
    }
    return axios({
        method: "GET",
        url: path,
        params: params,
        headers: headers
    });
};

sample

getApi("https://api.hogehoge.com/users/info", {user_id: 123});

POST

※ 一部のレガシー Android ブラウザでは動作しないため対処法を別記事に書きました。(https://qiita.com/naoiwata/items/fe93072b0acab28535a3)

import {forEach, keys} from "lodash";

let postApi = (path, params, headers) => {
    if (!params) {
        params = {};
    }
    let _params = new URLSearchParams();
    forEach(keys(params), (val) => {
        _params.append(val, params[val]);
    });
    if (!headers) {
        headers = {};
    }
    return axios({
        method: "POST",
        url: path,
        data: _params,
        headers: headers
    });
};

sample

postApi("https://api.hogehoge.com/users/create", {user_id: 123, name: "ほげ"});

Reference

16
20
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
16
20