跨域问题

76 阅读1分钟

www.bilibili.com/video/BV1sr…

同源: 两个页面的协议、域名、端口都相同,反之则是跨域
浏览器可允许发起跨域请求,但返回的数据会被浏览器拦截无法被也买你获取到

解决办法:
方法一:JSONP : 临时解决方案,只支持get请求 (不推荐) 实现原理:通过< script >标签的src属性,请求跨域的数据接口,并通过函数调用,接受跨域接口的响应数据

方法二:webpack proxy
在webpack.config.js中

var path = reqiure('path') // node中加载依赖包
var htmlWebpackPlugin = require('htnl-webpack-plugin')
module.exports ={
    // 入口文件 webpack是模块化打包,根据入口文件找到关联的所有文件
    entry:'./sre/index.js', 
   // 出口文件 打包后的文件目录在哪里 
    output:{
     filename:'index.js',
     path:path.resolve(__dirname,'dist') // 打包后的目录输出   __dirname node中的变量 相当于在当前目录下创建dist文件
     publicPath:'/'  // 资源路径
    },
    devServer:{
        proxy:{ // 代理
        'api':{
            target:'http://localhost:3000'
        }
        }
    }
    plugins:[
    new htmlWebpackPlugin({
    filename:'index.html',
    template:'index.html'
    })
    ]
   }

方法三: nginx反向代理

方法四:webpack plugin(插件)

image.png

方法五:cors(后端解决 推荐!

image.png