I'm currently building my first npm package which contain axios requests. There is something wrong when i want to add a file as a parameter in a request and i don't know why.
I'm using form-data library and fs to add my local file.
First i created an abstract class to add my token in a header for every requests and a post method that will be used by my other classes :
import axios from 'axios'
import url from '../utils/constants.js'
class ApiBase {
constructor(apiKey) {
if (this.constructor === ApiBase) {
throw new TypeError('Abstract class "ApiBase" cannot be instantiated directly');
};
let service = axios.create({
headers: {
'Authorization' : `Bearer ${apiKey}`
},
})
this.service = service
}
post(payload, path) {
return this.service.request({
method: 'POST',
url: url + path,
data: payload
})
}
}
export default ApiBase
My class which extends ApiBase :
import ApiBase from "./api_base.js";
import { default as FormData } from "form-data"
class MyClass extends ApiBase {
constructor(apiKey) {
super(apiKey)
}
formatData (files, providers, language) {
const user = new FormData();
const key = [
"files",
"providers",
"language",
];
const value = [
files,
JSON.stringify(providers),
language
];
for (let i = 0; i < value.length; i++) {
user.append(key[i], value[i]);
}
return user
}
myFeature = (files, providers, language) => {
const userData = this.formatData(files, providers, language);
return this.post(userData, 'endpointApi')
}
}
export default MyClass
Then i call myFeature in index.js to test it and try to console.log the api response :
import MyClass from './api/myclass.js'
import * as fs from 'fs';
const testFeature = new MyClass('MYAPIKEY')
var myFile = fs.createReadStream('./testData/Doc.jpg');
testFeature.myFeature(myFile,['microsoft'], "fr-FR").then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error.response.data);
});
When i send request with other features that not need files it works...
Maybe something went wrong with formData or something missing in the headers