聊一聊 跨域问题的解决方案

415 阅读1分钟

疑问 🤔️:是否在前端项目中遇到过这样的报错信息呢?

在检查元素中network
Referrer Policy: no-referrer-when-downgrade

或者在console中 出现Access to XMLHttpRequest at 'http://localhost:8080/......' from origin 'http://........' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

那么应该需要跨域来解决!!!

1.什么是跨域?

域名、协议、ip地址、端口号 任何一个不一样就是跨域

2.解决跨域?

  • 方案1:jsonp ---使用script的src发送 只能get请求.
  • 方案2:cors后台设置允许跨域 需要后台设置允许跨域 所有后台语言都可以设置.
   Access-Control-Allow-Origin:*
   Access-Control-Allow-Methods:"POST,GET,OPIONS,DELECT"
  • 方案3:服务器代理 1>重点现在vue框架是可以自己设置服务器代理的proxy vue 在vue.config.js可以配置重写webpack
module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
    configureWebpack: (config) => {
        //入口文件
        config.entry.app = ['babel-polyfill', './src/main.ts'];
    },
    devServer: {
		// 本地跨域代理,修改需要重新运行 yarn serve || npm run serve
        proxy: {
            '/api': {
                target: 'http:xxx.xx.xxx.xx:8080/',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': ''
                }
            },
            '/apu': {
                target: 'http:xxx.xx.xxx.xx:8080/',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/apu': ''
                }
            }
        }
    }
}