6
6

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 5 years have passed since last update.

プロトアウトスタジオAdvent Calendar 2019

Day 13

axiosのヘッダーのconfigでちょっとハマった

Posted at

某APIを試しててaxiosのconfig指定をミスってたので、自戒の意味を込めて残しておきます。

完全に自分用メモっぽいやつです。

ミスったコードなど


//省略

class Hoge {
    constructor() {
    	//省略
    }
    
    //ミスった方
    methodA(IMAGE_PATH){
        const file = fs.createReadStream(IMAGE_PATH);
        const form = new FormData();
        form.append('image', file);
        form.append('entrance', 'detection');
        
        const config = {
            'X-ClovaOCR-Service-ID': this.SERVICE_ID,
            ...form.getHeaders()
        };

        return axios.post(this.URL.RECOGNITION, form, config)
   }
   
   
   //うまくいった方
   methodB(IMAGE_PATH){
        const file = fs.createReadStream(IMAGE_PATH);
        const form = new FormData();
        form.append('image', file);
        form.append('entrance', 'detection');

        const config = {
            headers: {
                'X-ClovaOCR-Service-ID': this.SERVICE_ID,
                ...form.getHeaders(),
            }
        }

        return axios.post(this.URL.RECOGNITION, form, config)
   }
}

const hoge = new Hoge();
hoge.methodA(); // エラー
hoge.methodB(); // 成功

axiosのconfigミス

慣れてつかってるうちにconfig=headersっぽいイメージで使ってたみたい。
通常configの中には他にもmethod指定やbodyデータなども入ってくるのでconfig.headersな指定にしないとですね。

const config = {
	'X-ClovaOCR-Service-ID': this.SERVICE_ID,
    ...form.getHeaders()
};
const config = {
    headers: {
        'X-ClovaOCR-Service-ID': this.SERVICE_ID,
        ...form.getHeaders(),
    }
}
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?