開發必遇的問題 --- 跨域問題

1、什麼是跨域問題

當前頁面的 協議、域名、端口, 這三者之一與請求 url的不同,即爲跨域

在這裏插入圖片描述

協議不同

http://www.baidu.com
https://www.baidu.com

域名不同

https://www.baidu.com
https://taobao.com

端口不同

http://localhost:5500/index.html
http://localhost:6700/index.html

2、爲什麼會出現跨域問題

出於瀏覽器的同源策略限制,所謂同源就是兩個頁面具有相同的協議(protocol),主機(host)和端口號(port)

以前開發很少出現跨域問題,因爲基本都是後端 連同前端的一起開發的,

現在是前後端分離的開發模式,可能前端放在這個地址,後端接口放在那個地址,就會出現跨域問題

3、如何解決跨域問題

舉個例子,現在前端使用 webpack的項目,進行網絡請求

/* 網絡請求的js代碼 */
let xhr = new XMLHttpRequest();
xhr.open('get', 'http://www.xxxxxxxx.xxx/xxx', true);
xhr.onload = function() {
  console.log(xhr.response)
}
xhr.send()
/* webpack.config.js 的配置文件 */
const path = require('path')

module.exports = {
  // entry: 入口    output:出口
  entry: './src/main.js',
  output: {
    // path: 絕對路勁 , 需要動態獲取路勁
    // path.resolve(__dirname, 'dist') --> 將獲取當前項目的位置, 與dist進行拼接
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/'
  }
}

果不其然,遇到了跨域問題

在這裏插入圖片描述

3.1、前端:Webpack proxy

使用webpack的 proxy的方式來解決跨域問題,就是使用一種代理的方式,將網絡請求代理爲你要請求的接口

/* 將請求方式改變爲 本地的 http://localhost:5501/api/users */
let xhr = new XMLHttpRequest();
xhr.open('get', '/api/users', true);  // 改變
xhr.onload = function() {
  console.log(xhr.response)
}
xhr.send()
/* webpack.config.js 的配置文件 添加 proxy的代理模式 */
const path = require('path')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/'
  },
  devServer: {
    proxy: {  // 代理
      '/api': { // 將 /api 開頭的代理爲 target 的路徑
        target: 'http://www.xxxxxxxx.xxxx',
        pathRewrite: {'/api': ''}  // 去除/api這個字符串
      }
    }
  }

}

3.2、前端:Webpack plugin

3.3、中間件:nginx反向代理

3.4、後端:cors(推薦)

後端的我講不清楚,可以看看這篇博客:https://blog.csdn.net/qq_38128179/article/details/84956552

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章