When prompted ElementUI project requests SpringBoot backstage Project: Access to XMLHttpRequest at ** from origin ** has been blocked by CORS policy

Scenes

After the front end of the project to build ElementUI tips:

Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy

 

 

This is because there have been problems in the cross-domain request requesting the background SpringBoot interface.

Originally intended to be carried out before the project to build a good front-end data js ajaxq request, but it would be rejected because of the cross-domain.

Note:

Blog:
https://blog.csdn.net/badao_liumang_qizhi
public concern number of
programs overbearing ape
acquisition-related programming e-books, tutorials and push for free download.

achieve

Therefore, the use of background data request for axios

Installation axios

npm install axios

 

 

Then open the inlet program main.js added axios

axios import from  ' axios '

 

 

 

Then open proxy configuration url of webpack.config.js

  

devServer: {
    host: '127.0.0.1',
    port: 8010,
    proxy: {
      '/api/': {
        target: 'http://127.0.0.1:8088',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

 

 

 

以上配置代表项目的启动端口为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);

                })
            }

 

请求效果

 

 

Guess you like

Origin www.cnblogs.com/badaoliumangqizhi/p/12007336.html