首頁  >  文章  >  web前端  >  webpack開發跨域問題簡單探討

webpack開發跨域問題簡單探討

巴扎黑
巴扎黑原創
2017-08-13 14:41:241180瀏覽

這篇文章主要介紹了webpack開發跨域問題解決方法,小編覺得還挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

本文介紹了webpack開發跨域問題解決方法,分享給大家,具體如下:

1. 說明

webpack 內建了http-proxy-middleware 可以解決請求的URL 代理程式的問題

2. API

需要代理程式的pathname要加/


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.xxx.com 中
      '/device/*': { 
        target: 'http://debug.xxx.com',
        secure: false, // 接受 运行在 https 上的服务
        changeOrigin: true
      }
    }
  }
}

3. 使用

#:使用的url 必須以/開始否則不會代理到指定位址


  fetch('/device/space').then(res => {
    // 被代理到 http://debug.xxx.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);
  })

以上是webpack開發跨域問題簡單探討的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn