T
T
tonyshow2019-03-31 15:58:12
proxy
tonyshow, 2019-03-31 15:58:12

How to solve CORS issue when using local server and webpack dev server with proxy?

I am using a local web server (OpenServer) for a db site and php and webpack with webpack-dev-server for frontend development. I access the local server, through the webpack dev server proxy:

const webpack = require('webpack');
    const path = require('path');
    
    module.exports = params => ({
      devServer: {
        contentBase: params.path.public,
        publicPath: params.path.publicPath,
        compress: true,
        host: params.devServer.host, // anyships.site
        port: params.devServer.port, // 3000
        hot: true,        
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        openPage: 'ru',
        proxy: {
          '/': {
            target: params.devServer.proxy.path, // http://anyships.site (порт локального сервера: 80)
            changeOrigin: true,
          }
        }
      },
      plugins: [
        new webpack.HotModuleReplacementPlugin()
      ]
    });

When opening pages with ajax requests to the database to get data, I get the following response in the browser:
5ca0b93e5c699009611248.jpegAccess to XMLHttpRequest at ' anyships.site/ru/matrix/2892 ' (redirected from ' anyships.site:3000/matrix/2892 ') from origin ' anyships.site:3000 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values ​​'*, *', but only one is allowed .
Please tell me how to set up a proxy dev server to eliminate CORS blocking. Thanks in advance to everyone for help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tonyshow, 2019-03-31
@tonyshow

In general, he solved the problem! As the saying goes: "Saving the drowning is the work of the drowning themselves!"
The essence of what I'm doing is simply replacing host:port in the header address in the response from the local server (proxyRes.headers.location) with host:port webpack dev server'a and CORS goes nah ... (forest), because it doesn't he thinks that he is fucked ... (deceived) ))) and slipped another address.

devServer: {
    contentBase: params.path.public, // Путь до корневой дериктории, где dev server будет запрашивать файлы, которые не компилируются webpack'om
    // Например: c://web-site-path/public
    publicPath: params.path.publicPath, // Перфикс пути, по которому будут лежать файлы у вебпак дев сервера 
    // Например: '/public/assets/' - файлы будут доступны по адресу: http://anyships.site/public/assets/file_name.js
    host: 'anyships.site', // Host webpack dev server'a
    port: 3000, // Port webpack dev server'a
    hot: true, // Включить автоперезагрузку страницы при изменении файлов
    proxy: { // Собственно настройки прокси
      '**': { // С какого адреса webpack dev server'a будут проксироваться запросы на адрес локального сервера. 
        // В данном случае ** - значит все адреса проксировать, начиная с корня http://anyships.site:3000
        // Например: http://anyships.site:3000/user запрос на http://anyships.site/user (адрес из target ниже)
        target: `http://anyships.site`, // Целевой адрес локального сервера, куда будут проксироваться запросы с дев сервера 
        onProxyRes(proxyRes, req, res) {
          if (proxyRes.headers.location) { // Если есть заголовок со свойством location (Где храниться полный адрес запроса к локальному серверу)
            let location = proxyRes.headers.location; // Сохраняем адрес зоголовка location из ответа в переменную location
            console.log(`LOCATION: ${proxyRes.headers.location}`); // Выводит в консоль адрес до замены
            location = location.replace('anyships.site', 'anyships.site:3000'); // Заменяем адрес локального сервера на адрес webpack dev server'a
            proxyRes.headers.location = location; // Присваиваем в заголовок location подмененный адрес из переменной location
            console.log(`REPLACED: ${proxyRes.headers.location}`); // Выводит в консоль адрес после замены
          }
        }
      }
    }
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ]

5ca0ffd89decb123739532.jpegI hope my answer helps someone else besides myself! )) Good luck to everyone!

N
Nikolai Borzov, 2020-04-14
@chintsu

Thank you!
If you add the `access-control-allow-origin` header inside `onProxyRes`, then it does not appear in the resulting response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question