webpack解决跨域问题
webpack 解决前端跨域问题,只需要安装 webpack 的 http-proxy-middleware 模块就可以
npm install http-proxy-middleware --save-dev
配置如下:
module.exports = { devtool: 'cheap-module-source-map', entry: './app/js/index.js' output: { path: path.resolve(__dirname, 'dev'), // 所有输出文件的目标路径 filename: 'js/bundle.js', publicPath: '/', chunkFilename: '[name].chunk.js' }, devServer: { contentBase: path.resolve(__dirname, 'dev'), publicPath: '/', historyApiFallback: true, proxy: { // 请求到 '/device' 下 的请求都会被代理到 target: http://debug.mybj123.com 中 '/device/*': { target: 'http://debug.mybj123.com', secure: false, // 接受 运行在 https 上的服务 changeOrigin: true } } } }
使用如下:
fetch('/device/space').then(res => { // 被代理到 http://debug.mybj123.com/device/space return res.json(); }).then(res => { console.log(res); }) fetch('device/space').then(res => { // http://localhost:8080/device/space 访问本地服务 return res.json(); }).then(res => { console.log(res); })
注:使用的 url 必须以/开始 否则不会代理到指定地址
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » webpack解决跨域问题
码云笔记 » webpack解决跨域问题