webpack 解决跨域问题
一、webpack 内置了 http-proxy-middleware 可以解决 请求的 URL 代理的问题
安装:npm install --save http-proxy-middleware
二、要代理的 pathname 要加 /
示例:
devServer: {
contentBase: path.resolve(__dirname, 'dev'),
publicPath: '/',
historyApiFallback: true,
proxy: {
// 请求到 '/device' 下 的请求都会被代理到 127.0.0.1:3000 中
'/get/*': {
target: '127.0.0.1:3000',
secure: false, // 接受 运行在 https 上的服务
changeOrigin: true
}
}
}
三、例如fetch请求
fetch('/get').then(res => {
// 被代理到 127.0.0.1:3000/get
return res.json();
}).then(res => {
console.log(res);
})
fetch('device/space').then(res => {
// http://localhost:8080/get访问本地服务
return res.json();
}).then(res => {
console.log(res);
})
注:使用的url 必须以/开始 否则不会代理到指定地址
浙公网安备 33010602011771号