Advertisement
ErolKZ

Untitled

Mar 22nd, 2022
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1.  
  2. const host = `http://localhost:3030`;
  3.  
  4. async function request(method, url, data) {
  5. const options = {
  6. method,
  7. headers: {}
  8. };
  9.  
  10. if (data !== undefined) {
  11. options.headers['Content-Type'] = 'application/json';
  12. options.body = JSON.stringify(data);
  13. }
  14.  
  15. const user = JSON.parse(localStorage.getItem('user'));
  16. if (user) {
  17. const token = user.accessToken;
  18. options.headers['X-Authorization'] = token;
  19. }
  20.  
  21. try {
  22. const response = await fetch(host + url, options);
  23.  
  24. if (response.ok !== true) {
  25. if (response.status === 403) {
  26. localStorage.removeItem('user');
  27. };
  28. const error = await response.json();
  29. throw new Error(error.message);
  30. }
  31.  
  32. if (response.status === 204) {
  33. return response;
  34. } else {
  35. return response.json();
  36. }
  37.  
  38. } catch (err) {
  39. alert(err.message);
  40. throw err;
  41. }
  42. }
  43.  
  44. const get = request.bind(null, 'get');
  45. const post = request.bind(null, 'post');
  46. const put = request.bind(null, 'put');
  47. const del = request.bind(null, 'delete');
  48.  
  49. export {
  50. get,
  51. post,
  52. put,
  53. del as delete
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement