resolveConfig.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(
  14. buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
  15. config.params,
  16. config.paramsSerializer
  17. );
  18. // HTTP basic authentication
  19. if (auth) {
  20. headers.set(
  21. 'Authorization',
  22. 'Basic ' +
  23. btoa(
  24. (auth.username || '') +
  25. ':' +
  26. (auth.password ? unescape(encodeURIComponent(auth.password)) : '')
  27. )
  28. );
  29. }
  30. if (utils.isFormData(data)) {
  31. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
  32. headers.setContentType(undefined); // browser handles it
  33. } else if (utils.isFunction(data.getHeaders)) {
  34. // Node.js FormData (like form-data package)
  35. const formHeaders = data.getHeaders();
  36. // Only set safe headers to avoid overwriting security headers
  37. const allowedHeaders = ['content-type', 'content-length'];
  38. Object.entries(formHeaders).forEach(([key, val]) => {
  39. if (allowedHeaders.includes(key.toLowerCase())) {
  40. headers.set(key, val);
  41. }
  42. });
  43. }
  44. }
  45. // Add xsrf header
  46. // This is only done if running in a standard browser environment.
  47. // Specifically not if we're in a web worker, or react-native.
  48. if (platform.hasStandardBrowserEnv) {
  49. withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
  50. if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
  51. // Add xsrf header
  52. const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  53. if (xsrfValue) {
  54. headers.set(xsrfHeaderName, xsrfValue);
  55. }
  56. }
  57. }
  58. return newConfig;
  59. };