77 */
88
99const axios = require ( 'axios' ) ;
10+ const url = require ( 'url' ) ;
1011const ConfigUtils = require ( '../utils/ConfigUtils' ) ;
1112
1213const SecurityUtils = require ( '../utils/SecurityUtils' ) ;
@@ -31,6 +32,8 @@ function addHeaderToAxiosConfig(axiosConfig, headerName, headerValue) {
3132 axiosConfig . headers = assign ( { } , axiosConfig . headers , { [ headerName ] : headerValue } ) ;
3233}
3334
35+ const corsDisabled = [ ] ;
36+
3437/**
3538 * Internal helper that will add to the axios config object the correct
3639 * authentication method based on the request URL.
@@ -107,12 +110,15 @@ axios.interceptors.request.use(config => {
107110 let proxyUrl = ConfigUtils . getProxyUrl ( config ) ;
108111 if ( proxyUrl ) {
109112 let useCORS = [ ] ;
113+ let autoDetectCORS = false ;
110114 if ( isObject ( proxyUrl ) ) {
111115 useCORS = proxyUrl . useCORS || [ ] ;
116+ autoDetectCORS = proxyUrl . autoDetectCORS || false ;
112117 proxyUrl = proxyUrl . url ;
113118 }
114119 const isCORS = useCORS . reduce ( ( found , current ) => found || uri . indexOf ( current ) === 0 , false ) ;
115- if ( ! isCORS ) {
120+ const cannotUseCORS = corsDisabled . reduce ( ( found , current ) => found || uri . indexOf ( current ) === 0 , false ) ;
121+ if ( ! isCORS && ( ! autoDetectCORS || cannotUseCORS ) ) {
116122 const parsedUri = urlUtil . parse ( uri , true , true ) ;
117123 config . url = proxyUrl + encodeURIComponent (
118124 urlUtil . format (
@@ -123,10 +129,26 @@ axios.interceptors.request.use(config => {
123129 )
124130 ) ;
125131 config . params = undefined ;
132+ } else if ( autoDetectCORS ) {
133+ config . autoDetectCORS = true ;
126134 }
127135 }
128136 }
129137 return config ;
130138} ) ;
131139
140+ axios . interceptors . response . use ( response => response , ( error ) => {
141+ if ( error . config && error . config . autoDetectCORS ) {
142+ const urlParts = url . parse ( error . config . url ) ;
143+ const baseUrl = urlParts . protocol + "//" + urlParts . host + urlParts . pathname ;
144+ if ( corsDisabled . indexOf ( baseUrl ) === - 1 ) {
145+ corsDisabled . push ( baseUrl ) ;
146+ return new Promise ( ( resolve , reject ) => {
147+ axios ( { ...error . config , autoDetectCORS : false } ) . then ( resolve ) . catch ( reject ) ;
148+ } ) ;
149+ }
150+ }
151+ return Promise . reject ( error . response ? { ...error . response , originalError : error } : error ) ;
152+ } ) ;
153+
132154module . exports = axios ;
0 commit comments