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

场景

搭建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_第1张图片

 

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

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

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

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

安装axios

npm install axios

 

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS_第2张图片

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

import axios from 'axios'

 

ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS_第3张图片

然后打开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_第4张图片

以上配置代表项目的启动端口为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_第5张图片

 

你可能感兴趣的:(Vue,ElementUI)