Vue solves the cross-domain problem of axios

It's okay to be idle, knock on vue to request data during the holidays, and summarize the problem of vue crossing

The first. The server server does not support cross-domain requests

  1. When cross-domain requests cannot be made, we can modify the dev:{} part of index.js in the config folder under the project.

    Add the following code:

   proxyTable: {
         '/api' : {
            target: 'http://api.douban.com/v2',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },

 Set target to the domain name we need to access.

2. Then set the global property in main.js :

Vue.prototype.HOST = '/api'

3. We can use this domain name globally, as follows:

var url = this.HOST + '/movie/in_theaters'
    this.$http.get(url).then(res => {
      this.movieList = res.data.subjects;
    },res => {
      console.info( 'Call failed' );
    });

The second: server-side supports cross-domain

    String data = JsonUtil.toJsonNonNull(pubXtzdBos);
    
    OutputStream out = response.getOutputStream(); 
    
    out.write(data.getBytes( "UTF-8")); // encode in UTF-   8response.setHeader 
    
    ( "Access-Control-Allow-Origin", "*" );
     // Tell the browser the encoding method   
    response.setHeader("Content-Type","text/html;charset=UTF-8" );

If it can support cross-domain, then you can use jsonp to request. jsonp is actually added by adding script tags,

The data returned from the request is also in js format. Axios does not support it yet. You can only manually create the script tag yourself, assign the requested address to the src attribute of the script tag, and finally add it to the head tag. After the request returns, delete the tag:

   jsonpRequest: function (a, e) {
            this._ajaxTimer && clearTimeout(this._ajaxTimer);
            this._ajaxTimer = setTimeout(function () {
                
                var request_script = document.createElement('script');
                request_script.setAttribute("id", "request_script");   
                request_script.src = 'http://xxxx'+'&t=' + Date.now();
                window.callback = function (response) {
                    // 移除脚本
                    document.body.removeChild(document.getElementById('request_script'));
                    console.log(response.content);
                }
                document.body.appendChild(request_script);
            }, 500);
        },

To be honest, local development is suitable for the first one, and then you can use axios to make ajax requests normally.

         But this can only be used in development mode. When packaging and deploying, it is recommended to use nginx as a proxy

, I haven't tried the second one, and I also consulted the data summary, haha

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325066629&siteId=291194637