Created
December 22, 2017 10:15
-
-
Save Ajith-Pandian/7200f36b94bfcec4df7e2b86cbdee67b to your computer and use it in GitHub Desktop.
Api with multipart formdata and token
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
export default class Api { | |
static headers() { | |
return { | |
Accept: "application/json", | |
"Content-Type": "multipart/form-data" | |
}; | |
} | |
static get(route, token) { | |
return this.request(route, token, null, "GET"); | |
} | |
static put(route, token, params) { | |
return this.request(route, token, params, "PUT"); | |
} | |
static post(route, token, params) { | |
return this.request(route, token, params, "POST"); | |
} | |
static delete(route, token, params) { | |
return this.request(route, token, params, "DELETE"); | |
} | |
static request(route, token, params, verb) { | |
const host = "http://localhost:3000/";//SERVER BASE URL | |
const url = `${host}${route}`; | |
let formData = new FormData(); | |
for (let name in params) { | |
formData.append(name, params[name]); | |
} | |
let options = Object.assign( | |
{ method: verb }, | |
params ? { body: formData } : null | |
); | |
options.headers = { ...Api.headers(), token }; | |
return fetch(url, options) | |
.then(response => response.json()) | |
.then(responseJson => responseJson) | |
.catch(error => { | |
console.error(error); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment