【问题标题】:Using Fetch to gather information from a Backend API?使用 Fetch 从后端 API 收集信息?
【发布时间】:2021-12-26 19:57:13
【问题描述】:

在我的后端 (Ruby) 中,我调用了一个翻译 API,它返回翻译后的文本。然后,当用户单击我的 TranslationButton.vue 组件时,我需要显示此翻译后的文本,我不知道通过 fetch 正确访问我的后端 API。当我们提到后端 api 调用时,如何发现要使用的正确端点?

Messages.vue

methods {
    loadTranslations() {
      fetch('#whatgoeshere')
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson)
      });
    },
  }

request.rb

def make_request
    response = Faraday.post('https://api.deepl.com/v2/translate', auth_key: 'authkeyhere', text: @final_ticket, target_lang: 'DE', source_lang: 'EN')
    if response.status == 200
      body = response.body
      translated_text = body.split('"')[-2]
      return translated_text
    else
      raise InvalidResponseError unless response.success?
    end
  end

【问题讨论】:

    标签: javascript ruby vue.js


    【解决方案1】:

    为您的 make_request 方法设置路由。然后从你的前端击中那条路线。

    fetch("localhost:3000/make_request?maybe_some_query_param=whatever_you_are_translating") 和你所拥有的其余部分看起来不错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      相关资源
      最近更新 更多