欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

程序员文章站 2022-04-14 19:58:12
场景 搭建ElementUI前端项目后提示: Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy 这是因为在请求后台SpringBoot接口时出现了跨域请求问题。 本来打算是搭建好前端项目后再js中 ......

场景

搭建elementui前端项目后提示:

access to xmlhttprequest at **from origin ** has been blocked by cors policy

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

这是因为在请求后台springboot接口时出现了跨域请求问题。

本来打算是搭建好前端项目后再js中进行ajaxq请求数据,但是会因为跨域被拒绝。

注:

博客:

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

所以使用axios进行后台数据的请求

安装axios

npm install axios

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

然后打开入口程序main.js添加axios

import axios from 'axios'

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

 

然后打开webpack.config.js进行url的代理配置

  

devserver: {
    host: '127.0.0.1',
    port: 8010,
    proxy: {
      '/api/': {
        target: 'http://127.0.0.1:8088',
        changeorigin: true,
        pathrewrite: {
          '^/api': ''
        }
      }
    },

 

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

以上配置代表项目的启动端口为8010,elementui在向后台请求url时,就会将/api/的请求想target中执行的地址去请求

所以我们可以在页面app.vue中这样去调用后台数据接口

//页面初始化的时候,去调用
        created: function(){
            debugger
            this.getdata()
        },
        methods: {
            //通过ajax去请求服务端,获取数据
            getdata() {
                debugger
                let url = "/api/user/selectalllimit?offset=2&limit=1" ;
                this.$axios.get(url).then((res) => {

                    this.tabledata = res.data;//把传回来数据赋给packdata

                }).catch(function(error){

                    console.log(error);

                })
            }

 

请求效果

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy