How can you utilize Fetch to retrieve data from a Backend API?

One challenge I am facing is how to correctly access my Backend API in Ruby to fetch translated text from a translation service. Specifically, I am unsure about the correct endpoint to use when making the backend API call.

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

Answer №1

Create a route specifically for your make_request function. Once it's set up, trigger this route from your frontend.

For example, use

fetch("localhost:3000/make_request?maybe_some_query_param=whatever_you_are_translating")
and everything else seems to be in order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the focus() method is used to programmatically set the cursor in a JQuery input element, the blinking cursor does

I have a situation where I have two sibling divs. On the left side, I am loading a PDF document, while on the right side, I have input fields controlled by jQuery. My challenge arises when I try to select and delete the value from the input using the mous ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

Unable to proceed to the following stage after returning when using vee-validate

I am currently utilizing vee-validate v3 for validating a multi-step form and then making an axios call. I have implemented handleSubmit along with ValidationObserver with unique keys for each step. However, I am facing an issue where, after progressing to ...

I am having difficulty retrieving the JSON object that was sent by the servlet

$(document).ready(function() { var path = null; console.log('${pageContext.request.contextPath}/loadfile'); $.ajax({ dataType: "json", url: '${pageContext.request.contextPath}/loadfile&apos ...

Finding the index number of a DIV element when it is clicked

Here is an example of the HTML structure I am working with: <div id="preview-wrapper"> <div class="dz-preview dz-image-preview"> <a class="rotate-a" href="javascript:void(0);"> <img class="rotate" src="public/a ...

Exploring (nested) data structures in JavaScript

I'm struggling to understand if my issue lies in how I am organizing my array or in how I am accessing it. The idea is simple: I want to have an array of car makes and models that I can access for display purposes. const carBrands = [ { Audi: { ...

Printing in Firefox is ineffective, but functions smoothly in alternative browsers

I'm currently working on customizing some content specifically for printing, so I've implemented a hook import { useState } from 'react' const usePrint = () => { const [isPrinting, setIsPrinting] = useState(false) const hand ...

Go back to the previous operation

Utilizing ajax to verify if a username is available by checking the MySQL database. If the username is already taken, it will return false to the form submit function. index.php $("#register-form").submit(function(){ var un = $("#un").val(); $.aj ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Firebase (web) deploy encounters an issue due to stripe integration

I recently integrated Stripe into my Firebase function index.js: const stripe = require('stripe')('key'); and created a function for checkout sessions: exports.createCheckoutSession = functions.https.onCall(async(data, context) =&g ...

Is it more effective to specify the class within the selector when using jQuery to remove a class?

Does including the class in the selector when removing a class using jQuery have any impact on performance or best practices? I'm curious if there will be any noticeable difference. For example, do you include it like this: $('#myList li.classT ...

Incorporating hCaptcha into Laravel Jetstream with Inertia.js

Currently utilizing Laravel 8 together with Jetstream 2.0 and the Inertia stack. Successfully added the Vue hCaptcha component from here to my login form. The Vue component is functioning perfectly. Followed the instructions provided in this guide to se ...

Error in Node.js: Unable to access properties of null value within Express

While using Express (with node.js) and MongoDB, I encountered an error when trying to view or update a user profile. The middleware token check worked fine getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (rea ...

Retrieve the ID of the button that was chosen

Hello, I have a card with 3 selectable buttons as described below. <ul class="nav nav-tabs border-0" role="tablist" id="FlightType" onclick="SelectedFlightType()"> <li cla ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

Dealing with null exceptions in Angular 4: Best practices

Hi there, I am encountering an issue with binding my model data to HTML fields where when I try to edit the data it returns an error saying "cannot read value of null". How can I resolve this? Here is the HTML code snippet: <div class="form-group"> ...

The problem with React useState not updating could be due to useRef interference

I'm facing a strange issue with my React code: the useState function is not updating the view, despite trying everything to fix it. To illustrate the problem, I have created a simple example: function(){ const [enterJob, setEnterJob] = useSt ...

How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example: $scope.test = "blah"; $scope.watch("test", function(new, old){ console.log(ne ...

Extract the email address from the HTML source code obtained through a GET AJAX request

An interesting scenario arises when the following code is executed from www.example.com. It fetches the complete html source code of www.example.com/example.html and displays it in an alert message. function process(){ url = "http://www.example.com/ex ...

Difficulty switching back and forth between three varying heights

I have a container with a button labeled "Show more". Upon clicking the button, the height of the container will transition through 3 different states. <div class="segment-suggestion-content height-small"> <div class="segment-suggestion-sh ...