2015-07-24 17 views
16

Sto usando webpack-dev-server v1.10.1 per incrementare il mio progetto Redux e ho le seguenti opzioni:webpack server di dev problema CORS

contentBase: `http://${config.HOST}:${config.PORT}`, 
quiet: false, 
noInfo: true, 
hot: true, 
inline: true, 
lazy: false, 
publicPath: configWebpack.output.publicPath, 
headers: {"Access-Control-Allow-Origin": "*"}, 
stats: {colors: true} 

Nel JS, io sto usando request da superagent per generare un HTTP GET chiamare

request 
      .get(config.APIHost + apiUrl) 
      .set('Accept', 'application/json') 
      .withCredentials() 
      .end(function (err, res) { 
       if (!err && res.body) { 
        disptach(() => { 
         return { 
          type: actionType || GET_DATA, 
          payload: { 
           response: res.body 
          } 
         } 
        }); 
       } 
      }); 

Ma ho ottenuto l'errore CORS:

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access 

Qualsiasi Sugg stato per risolvere questo? Grazie mille

risposta

5

Stai utilizzando il tuo JavaScript da localhost:5050 ma il tuo server API è localhost:8000. Questo viola la stessa politica di origine, quindi il browser non lo consente.

è possibile modificare il server API in modo che CORS is enabled, o seguire the instructions on the webpack-dev-server page in "La combinazione con un server esistente" per combinare bene servire con webpack-dev-server e il proprio server API.

18

Con webpack-dev-server di 1.15.X è possibile utilizzare questa configurazione nel file di configurazione:

devServer: { 
    contentBase: DIST_FOLDER, 
    port: 8888, 
    // Send API requests on localhost to API server get around CORS. 
    proxy: { 
     '/api': { 
     target: { 
      host: "0.0.0.0", 
      protocol: 'http:', 
      port: 8080 
     }, 
     pathRewrite: { 
      '^/api': '' 
     } 
     } 
    } 
}, 

Con questo esempio si reindirizzare tutte le chiamate http://0.0.0.0:8888/api/*-http://0.0.0.0:8080/* e CORS risolto

6

altro per ovviare al problema è necessario aggiungere direttamente le intestazioni CORS necessarie al server di sviluppo:

devServer: { 
    ... 
    headers: { 
    "Access-Control-Allow-Origin": "*", 
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", 
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" 
    } 
} 
Problemi correlati