vue中的axios引入方式和跨域问题

用localhost进行本地测试的时候,调用第三方接口会报跨域的错误 ,如果想在localhost下正常调用第三方接口的域名,需要进行如下配置

  1. 配置 proxyTable {}
module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: ‘static‘,
    assetsPublicPath: ‘/‘,
    *proxyTable: {
      "/baidu_music_api": {
            target: "http://tingapi.ting.baidu.com",
            changeOrigin: true,
            pathRewrite: {
                ‘^/baidu_music_api‘: ‘‘
            }
       }*
    },

    // Various Dev Server settings
    host: ‘localhost‘, // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
  1. main.js中启用代理
import router from ‘./router‘
Vue.prototype.HOST = "/baidu_music_api"
。。。
new Vue({
  el: ‘#app‘,
  **router,**
  components: { App },
  template: ‘<App/>‘
})

安装网络请求框架axios

  1. npm install axios --save
  2. main.js 引入,挂载,使用
import router from ‘./router‘
Vue.prototype.$axios  = Axios;
new Vue({
  el: ‘#app‘,
  router,
  components: { App },
  template: ‘<App/>‘
})
mounted(){
    var url = this.HOST + "/v1/restserver/ting?method=baidu.ting.billboard.billList&type="+ this.type +"&size=6&offset=0";
    this.$axios.get(url)
    .then(res => {
      this.todayRecommend = res.data.song_list
    })
    .catch(error => {
      console.log(error);
    })
  }

vue中的axios引入方式和跨域问题

上一篇:如何在 Apple TV 上使用矩形屏幕键盘?


下一篇:spring配置文件(application.properties、application.yml、application.yaml))中的配置项加载到自定义类中的方法