LoginSignup
62
38

More than 1 year has passed since last update.

vue.jsでaxios使ってのGET時にカスタムヘッダーが効かない対処法

Last updated at Posted at 2018-12-20

結論

空でいいから data:{}を付与する。

axios
 .get("http://localhost:8081/hogehoge/getContents", {
    headers: { "Content-Type": "application/json" },
    data: {} //←これ!!!
})
.then(response => {
  this.gridData = response.data.contents;
});

経緯

Content-Typeapplication/json を指定しないと弾くAPIサーバにアクセスしたかった。
そのためカスタムヘッダーを指定してみるも、chromeの開発者ツールで見る限り付与されていないようだった。

いない・・・
スクリーンショット 2018-12-20 12.24.00.png

調べてみたところ、axiosのissueにてそれっぽいものをみつけた
https://github.com/axios/axios/issues/86

data:{}指定したらいいよ」というコメントをみつけたので試した。
スクリーンショット 2018-12-20 12.24.00のコピー.png

よかった🤗

なぜって話はコメント読んでみてください。ここあたりから書いてるみたいです。要はContent-Typeで指定される対象となるコンテンツがないからそりゃ無いよね、だから空でいいからそのコンテンツ指定しようぜって話のようです。
https://github.com/axios/axios/issues/86#issuecomment-311788525

@teleyinex Content-Type describes what format the request data is in. If there is no request data, there is no need to specify the Content-Type. So you can correct me if I'm wrong but I believe the present behavior makes sense, aside from the fact that it should still not add the header if data is null. What do you think?

62
38
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
62
38