Source: util/fetch.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. const DEFAULT_INIT = {
  15. credentials: 'include',
  16. };
  17. /**
  18. * Fetches a resource. A thin wrapper around ES6 Fetch API, with standardized
  19. * default configuration.
  20. * @param {!string|!Request} resource The URL to the resource, or a Resource
  21. * object.
  22. * @param {Object=} init An optional object containing custom configuration.
  23. * @return {Promise} A Promise that resolves to a Response object.
  24. */
  25. export default function defaultFetch(resource, init = {}) {
  26. const headers = new Headers({'x-csrf-token': Liferay.authToken});
  27. new Headers(init.headers || {}).forEach((value, key) => {
  28. headers.set(key, value);
  29. });
  30. const mergedInit = {
  31. ...DEFAULT_INIT,
  32. ...init,
  33. };
  34. mergedInit.headers = headers;
  35. // eslint-disable-next-line @liferay/portal/no-global-fetch
  36. return fetch(resource, mergedInit);
  37. }