溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

webpack開發(fā)跨域問題解決辦法

發(fā)布時間:2020-09-16 15:00:29 來源:腳本之家 閱讀:174 作者:mjzhang1993 欄目:web開發(fā)

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

1. 說明

webpack 內(nèi)置了 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'),
    // 所有輸出文件的目標(biāo)路徑
    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 上的服務(wù)
        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 訪問本地服務(wù)
    return res.json();
  }).then(res => {
    console.log(res);
  })

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI