0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AxiosでAPIを叩いたら設定は正しいのに401エラーが発生する

Posted at

はじめに

AxiosでPOSTリクエストをする際にかなり時間がかかってしまったのでまとめていきます。
内容は正しいのになぜだろうと、原因がわからないときに確認してみてください

問題

以下の関数でRedmineにPOSTリクエストを送りました

Popup.tsx

  const fetchData = async () => {
    const data = JSON.stringify({
      issue: {
        project_id: "100",
        tracker_id: "4",
        subject: 新規チケット作成",
        description: "APIで作成しました",
        status_id: "1",
        priority_id: "4",
        custom_fields: [{ id: 105, name: "Job No", value: "12345" }],
      },
    });
    try {
      const res = await axios.post(
        "https://redmine-sample/issues.json",
        {
          headers: {
            "X-Redmine-API-Key": "12345",
            "Content-Type": "application/json",
          },
          data,
        }
      );
      return res.data;
    } catch (e) {
      console.log(e);
    }
  };

  const onClick = () => {
    const res = fetchData();
    console.log(res);
  };

しかしこのAxiosを叩くとなぜか401 Unauthorizedというエラーが返ってきます
何故エラーになっているのかがエラーレスポンスからわからないので苦戦しました

解決方法

まずはPostmanから実際に動いているリクエストを<>ボタンからコード出力してnode.jsaxiosコードとして出力し、確かめてみました

そうすると問題なくAxiosがリクエストを送ることができました

動いたAxiosと動かないAxiosを比べたところAxiosのURL以下のHeaderBodyを渡す引数の順番に問題がありました

問題となっているコードはheader, dataの順に対してPostmanのコードはdata, headerになっていました。
よくよく考えたら間違えいているのですが気づけずにいました

順序を変えることで問題なく動きました

Popup.tsx

  const fetchData = async () => {
    const data = JSON.stringify({
      issue: {
        project_id: "100",
        tracker_id: "4",
        subject: "新規チケット作成",
        description: "APIで作成しました",
        status_id: "1",
        priority_id: "4",
        custom_fields: [{ id: 105, name: "Job No", value: "12345" }],
      },
    });
    try {
      const res = await axios.post(
        "https://redmine-sample/issues.json",
        data,
        {
          headers: {
            "X-Redmine-API-Key": "12345",
            "Content-Type": "application/json",
          },
        }
      );
      return res.data;
    } catch (e) {
      console.log(e);
    }
  };

おわりに

実際の原因は単純だったのですが、API側が悪いのではないか、POSTしている情報がたりないのではないかなど色々深追いしてしまって時間がかかってしまいました

普段当たり前のようにやっていることだったのでここでエラーになっているとは思いませんでした
デバックをするのは大切です

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?