resolveConfig.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import platform from "../platform/index.js";
  2. import utils from "../utils.js";
  3. import isURLSameOrigin from "./isURLSameOrigin.js";
  4. import cookies from "./cookies.js";
  5. import buildFullPath from "../core/buildFullPath.js";
  6. import mergeConfig from "../core/mergeConfig.js";
  7. import AxiosHeaders from "../core/AxiosHeaders.js";
  8. import buildURL from "./buildURL.js";
  9. export default (config) => {
  10. const newConfig = mergeConfig({}, config);
  11. let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
  12. newConfig.headers = headers = AxiosHeaders.from(headers);
  13. newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
  14. // HTTP basic authentication
  15. if (auth) {
  16. headers.set('Authorization', 'Basic ' +
  17. btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
  18. );
  19. }
  20. if (utils.isFormData(data)) {
  21. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
  22. headers.setContentType(undefined); // browser handles it
  23. } else if (utils.isFunction(data.getHeaders)) {
  24. // Node.js FormData (like form-data package)
  25. const formHeaders = data.getHeaders();
  26. // Only set safe headers to avoid overwriting security headers
  27. const allowedHeaders = ['content-type', 'content-length'];
  28. Object.entries(formHeaders).forEach(([key, val]) => {
  29. if (allowedHeaders.includes(key.toLowerCase())) {
  30. headers.set(key, val);
  31. }
  32. });
  33. }
  34. }
  35. // Add xsrf header
  36. // This is only done if running in a standard browser environment.
  37. // Specifically not if we're in a web worker, or react-native.
  38. if (platform.hasStandardBrowserEnv) {
  39. withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
  40. if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
  41. // Add xsrf header
  42. const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  43. if (xsrfValue) {
  44. headers.set(xsrfHeaderName, xsrfValue);
  45. }
  46. }
  47. }
  48. return newConfig;
  49. }