What is the best way to send an axios request in a Vue component to a route created by an Adonis controller?

My WidgetController.js file is responsible for handling CRUD operations on the database. Within this controller, there is a method/generator called * create (request, response) which returns widget attributes in a response and also inserts a new row into the database's widgets table. The corresponding route is defined as

Route.any('widgets/create', 'WidgetController.create').as('widgets.create').middleware('auth');
. I am looking to trigger the create method by clicking a button on the frontend, so I attempted to import it within my Vue template:

<template>
    <div> 
        <button @click="createWidget">Click me</button>
    </div>
</template>
<style></style>
<script type="text/javascript">
    import WidgetController from '/path/to/WidgetController.js';
    export default{
        name: 'widget',
        data () {
            return{
                WidgetCtrl: WidgetController                
            }
        },
        methods: {
            createWidget () {
                return this.WidgetCtrl.create();
            }
        }
    }
</script>

However, this approach did not work due to dependencies and functions that are specific to AdonisJS and not available in Vue. I have heard about using axios to achieve similar functionality. How can I implement this?

Answer №1

It is not possible to directly import or access a server-side JavaScript file from the client side. In this case, you are attempting to import Adonis's WidgetController.js from Vue.js.

To achieve the desired functionality, you will need to make an HTTP request within the 'createWidget' function and target the create method within WidgetController.

Example of Vue's component file:

<template>
    <div> 
        <button @click="createWidget">Click me</button>
    </div>
</template>

<script type="text/javascript">

    export default{
        name: 'widget',
        data () {
            return{
                WidgetCtrl: WidgetController                
            }
        },
        methods: {
            createWidget () {
                axios.get('/url-point-to-WidgetController.create')
                     .then(response => {
                         // perform additional tasks
                      });
            }
        }
    }
</script>

Example of Adonis's WidgetController.js:

'use strict'

class WidgetController {

    * create(request, response) {
       // save widget...
    }

}

module.exports = WidgetController

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

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Applying a consistent script with varying inputs on the same HTML page

Is it possible to create a JavaScript code that can be used across different sections of an HTML document? The goal is for the script to fetch data such as title, runtime, and plot from a specific URL request and insert this information into the appropriat ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

What could be causing the second image to not drop in the proper position in an HTML and JavaScript environment?

I am encountering an issue with a simple drag and drop implementation using images in my code. The first image works fine, but for some reason the second image does not display correctly when dragged inside the div boxes; it appears outside of the box. Can ...

There seems to be an issue with React-hook-form and material-ui not retaining value changes in the onBlur() method

Stepping into the realm of react-hook-form is a new experience for me. I'm putting in effort to grasp everything, but there are still some pieces missing from the puzzle. Seeking assistance akin to Obiwan Kenobi! The Dilemma at Hand: An <Textfiel ...

Determine using Javascript or jQuery whether the value of input1 is greater than the value of input2

Ensuring that Value1 is always greater than Value2 in a form submission is crucial. If Value1 becomes greater than or equal to Value2, an error message should be displayed and the form submission should not be processed. Below is the code for the form: & ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

The iteration of an ajax POST handler, looping endlessly

Attempting to implement a basic ajax submit handler for modifying a form as part of a lesson on CSRF vulnerabilities, but encountering an issue with the page looping. Below is the code snippet being worked on, inspired by http://api.jquery.com/jQuery.post/ ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

Creating a Commitment - Resolving the "Expected ')' after argument list" Error

Can someone please help me locate the syntax error in this code snippet? I've been searching for ages! An error occurred: Uncaught SyntaxError: missing ) after argument list promiseArray.push( new Promise(function (resolve, reject) { ...

Why is my NextJs app loading slowly on Safari but quickly on Chrome?

Currently, I am in the process of developing a web app using nextjs. I have encountered some issues with linking to pages, particularly the home page which contains multiple svgs and images. The performance lags when using Safari, as it does not show a loa ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Tips for eliminating white spaces when text wraps onto a new line

Imagine having the following code snippet. Essentially, I have a layout that needs to display 'vs prev period' with a percentage in the same line. To achieve this, I utilized display: flex. The issue arises when we require the gap between the tw ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

Learn how to implement console-like Tail functionality in a web application using the MaterialUI TextField component as the console interface

Issue with Component: Scroll not Updating as new content is added to TextField: I am currently in the process of developing a live console feature within a React application and I wanted to utilize MaterialUI's TextField component since my app alread ...

Converting an HTML page into a JSON object by scraping it

Is there a way to convert an HTML page into a JSON object using web scraping? Here is the content of the page: <html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href ...

What is the process for retrieving data from a javascript file that was submitted through a form?

Can you help me with an issue I'm having with this code snippet? <form action="main.js"> <input type="text" required="required" pattern="[a-zA-Z]+" /> <input type="submit" value="Submit" /> </form> After c ...