vue本地和生产跨域请求,跨域请求Uncaught SyntaxError: Unexpected token错误

跨域请求路由配置

    proxyTable: {
      '/baiduApi': {  //前缀匹配
        target: 'http://api.map.baidu.com', //接口域名
        changeOrigin: true,  //是否跨域
        secure: false,  //https需要设置为true
        pathRewrite: {
          '^/baiduApi': '/',  //将url中baiduApi替换为/
        }
      }
    },

本地环境重启项目就能访问,在生产环境需要配置nginx中server,否则会出现404错误

^~ /baiduApi/表示匹配前缀是baiduApi的请求

proxy_pass的结尾有/, 则会把/baiduApi/*后面的路径直接拼接到后面,即移除baiduApi

    location ^~ /baiduApi/ {
        proxy_pass https://api.map.baidu.com/;
    }

请求出现Uncaught SyntaxError: Unexpected token错误,设置dataType为jsonp即可解决

    $.ajax({
      url:'/baiduApi/geocoder/v2/?output=json&ak=ak&address=xx',
      type:'get',
      dataType:'jsonp',
      success:function(data){
        console.log('success:'+data)
      },
      error:function(error){
        console.log(error)
      }
    })

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章