Created
April 8, 2020 14:55
-
-
Save mrcoles/a1e8725a7dc2dfc41536251a99851b44 to your computer and use it in GitHub Desktop.
An example of making an AxiosRequestConfig object to do a multipart/form-data request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { | |
AxiosRequestConfig, | |
Method, | |
} from 'axios'; | |
export const makeAxiosRequestConfig = ( | |
method: Method, | |
path: string, | |
data?: { [key: string]: any }, | |
params?: any | |
): AxiosRequestConfig => { | |
let headers: AxiosRequestConfig['headers'] = {}; | |
let formData: FormData | undefined = undefined; | |
if (data) { | |
headers['Content-Type'] = 'multipart/form-data'; | |
formData = new FormData(); | |
Object.entries(data).forEach(([key, val]) => { | |
// HACK - make type happy… | |
const hackVal = val as string | File; | |
formData.append(key, hackVal); | |
}); | |
} | |
return { | |
method, | |
url: `${ENDPOINT}${path}`, | |
data: formData, | |
params, | |
headers, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This handles both regular and form data, so you can send files to your server. You would use it like…