面试题系列---【vue 怎么实现跨域】

1.使用 vue-cli 脚手架搭建项目时 proxy 解决跨域问题 ,在项目目录下配置vue.config.js文件:

module.exports={
    // hash: publicPath ""
    // history: publicPath "/"
    publicPath:"",
    assetsDir:"static",
    outputDir:"dist",
    indexPath:"index.html",
    devServer:{
        proxy:{
            "/api":{
                target:"http://localhost:3000",//源地址
                ws:true,//改变源
                changeOrigin:true
            }
        }
    }
}

2.使用 CORS(跨域资源共享)

1、前端设置: 前端 vue 设置 axios 允许跨域携带 cookie(默认是不带 cookie) axios.defaults.withCredentials = true;

2、后端设置:

    1、 跨域请求后的响应头中需要设置:

    2、 Access-Control-Allow-Origin 为发起请求的主机地址。

    3、 Access-Control-Allow-Credentials,当它被设置为 true 时,允许跨域带 cookie,但此时 Access-Control- Allow-Origin 不能为通配符*。

   4、 Access-Control-Allow-Headers,设置跨域请求允许的请求头。

   5、 Access-Control-Allow-Methods,设置跨域请求允许的请求方式。

posted on 2021-06-16 21:48  码农小小海  阅读(387)  评论(0编辑  收藏  举报

导航