• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
IT-nose
博客园    首页    新随笔    联系   管理    订阅  订阅

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 必须以/开始 否则不会代理到指定地址

posted @ 2018-07-24 16:52  detanx_墨鼬漓  阅读(801)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3