Edited at

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

More than 1 year has passed since last update.


コード


準備

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

https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format