完美解决:No ‘Access-Control-Allow-Origin‘ header is present on the requested resource

已解决:No ‘Access-Control-Allow-Origin‘ header is present on the requested resource

目录

1.问题描述

​2.解决过程


1.问题描述

前端是vue,后端是springcloud,完全的前后端分离的项目,前端在向后端发送请求的时候出现如下的错误No ‘Access-Control-Allow-Origin‘ header is present on the requested resource


2.解决过程

分析:当我们请求一个接口的时候,出现如:Access-Control-Allow-Origin 字眼的时候说明请求跨域了。那什么是跨域呢?

所有使用JavaScript的浏览器都会支持同源策略。同源策略即指域名/协议/端口号相同。只要有一个不同,就会当作跨域请求

方案一:后端接口做如下配置,

 方案二:可以前端设置代理

在项目根目录下新建vue.config.js文件,在该文件内新增配置

module.exports = {
    devServer: {
        proxy: {
            '/test': {
                target: 'https://baidu.com',
                ws: true,
                changeOrigin: true,
                pathRewrite: {
                    '^/test': '' //遇到接口路径有test的,就换成http://www.baidu.com/这个请求头,同时把test去掉
                }
            }
        }
    },
}

把我工作中遇到的问题和解决的问题的过程记录下来,同时希望也可以帮到大家!

猜你喜欢

转载自blog.csdn.net/white0718/article/details/131889962
今日推荐