Answer the question
In order to leave comments, you need to log in
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()
]
});
Answer the question
In order to leave comments, you need to log in
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()
]
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 questionAsk a Question
731 491 924 answers to any question