首页 > 解决方案 > 在服务器上调用 axios,但在页面上调用 axios,而不是在启动时获取或异步数据

问题描述

我有一个简单的 nuxt 页面,它fetch从服务器(axios)中提取数据以填充表以进行初始加载,效果很好。

import axios from 'axios'
import CONST from '@/store/settings.js'
import mix from '@/components/mymixin'

export default {
  mixins: [ mix ],
  data() {
    return {
      msg: new Date(),
      domains: [],
      fields: [{
        key: 'name',
        label: 'Domain',
        sortable: true
      },{
        key: 'status', 
        label: 'Status'
      },{
        key: 'development_mode',
        label: 'Bypass CF',
        formatter: value => (value != '0') ? true : false, 
        sortable: true
      },{
        key: 'paused',
        label: 'Paused', 
        sortable: true
      },{
        key: 'actPageRules',
        label: 'Page Rules'
      }],
    }
  },
  methods: {
    info ( item, ix ) {
      axios.get( `${CONST.base}/zones/${item.id}/pagerules`, { headers: CONST.headers })
      .then( (res) => { console.log( res.data ) })
    }
  },
  mounted() {
    var me = this
    setInterval(function(){
      me.msg = new Date()
    }, 1000 )
    this.domains = this.$store.state.domains
  },
  fetch ( { store, params  } ) {
    const domains   = store.$axios.get( `${CONST.base}/zones?per_page=${CONST.pg}&account.id=${CONST.uid}`, { headers: CONST.headers })
      .then( (res) => { store.state.domains = res.data.result })
    // const registrar = axios.get( `${CONST.base}/accounts/${CONST.uid}/registrar/domains`, { headers: CONST.headers })
    //   .then( (res) => { this.domains = store.state.registrar = res.data.result })
    return Promise.all([ domains ])
  }, 
  asyncData( { store, params } ){

  }
}

我的表格模板是这个

<b-table class="table-responsive" striped hover :fields="fields" :items="domains">

  <template v-slot:cell(name)="data">
    <a :href="`#${data.value}`">{{ data.value }}</a>
  </template>

  <template v-slot:cell(development_mode)="data">
    <b-form-checkbox v-model="data.value" name="devmode" switch />
  </template>

  <template v-slot:cell(paused)="data">
    <b-form-checkbox v-model="data.value" name="paused" switch/>
  </template>

  <template v-slot:cell(actPageRules)="data">
    <b-button size="sm" @click="info(data.item)" class="mr-1" variant="warning">
      Page Rules
    </b-button>
  </template>
</b-table>

并且表格正确呈现。现在,我想用服务器上的info方法触发axios.get

我得到的错误是由于 CORS 我无法在客户端上运行它..

在此处输入图像描述

所以我的问题是,如何触发(通过点击或无论如何)方法在服务器上而不是在客户端上运行?

非常感激

标签: corsaxiosnuxt.js

解决方案


经过大量使用字符串关键字的谷歌搜索后,我明白了

- 对于其他偶然发现这里的 Google 员工,为了能够防止 CORS 错误并向某些远程 API 发出服务器请求(在我的情况下,它是 CloudFlare 和 MailChimp + Godaddy 用于 DNS),我们必须通过我们的服务器代理我们的请求!

此页面包含我们自己放置和构建它的所有详细信息>

https://axios.nuxtjs.org/options


推荐阅读