Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below:

<img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/>

Alongside, there is a method structured in this manner:

 async action() {
      let imgAttribute = event.target.getAttribute('word');
      alert(imgAttribute ); // The alert successfully displays the value
      console.log("imgAttribute : " + imgAttribute ); // The console log outputs properly

     await axios.post('http://localhost:3000/my/endpoint',
         {
           params: {
             word: imgAttribute 
           }
         });
...

Thus, when the user clicks on the <img> element, the action method gets executed. The value of the attribute word is captured and stored in the imgAttribute variable, which is then passed as a parameter in the post request.

The fact that both alert(imgAttribute) and console.log(imgAttribute) deliver the correct values suggests that they are functioning without any issues and displaying the intended string values contained within the word attribute.

Nevertheless, upon reaching the Express server:


app.post('/my/endpoint', async (req, res) => {
    const {word} = req.params;  // Attempted with req.query as well but faced the same dilemma with an undefined result
    console.log("word = " + word); // Outputs 'undefined'
...

Mysteriously, the word appears to be undefined at this stage.

What could be causing this issue? How can it be rectified?

Answer №1

To transfer data as a parameter instead of in the body using .post method, you can do:

  await axios({
    url: 'http://localhost:3000/my/endpoint',
    method: 'post',
    params: {
        word: imgAttribute 
    }
  })

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

Having trouble getting Node/Express to respond to POST requests

I am currently working on an AngularJS front-end communicating with a Node/Express/MySQL backend. All requests are functioning properly except for a POST request. Below is the Angular code I have: var Data = $resource('http://127.0.0.1:9001/api/data_ ...

The Material-UI table spills out of its designated container

My material-ui table is resizing and scrolling horizontally without issue, but the table element and its contents are overflowing off the right side of the page. Check out this gif to see the behavior: https://i.stack.imgur.com/lXuHj.jpg Additionally, her ...

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

What is the best way to extract specific data from a CSV file and incorporate it into a JSON object using csvparser?

I'm relatively new to nodejs and am working on a project where I need to extract data from a CSV file containing COVID information for various countries and US states. My goal is to filter out only the US states from this data and display it in a tabl ...

Guide to activating a reaction following an occurrence in a React component

I have started developing a React application that loads blog posts along with their associated comments. The challenge I am facing is how to trigger a refresh of the comments component and display the new comment immediately after it has been submitted. ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Error: The function SomeFunction is not recognized as a valid function (Mongoose library)

Help needed! I'm encountering an error stating "TypeError: User.getUserByUsername is not a function at Strategy._verify (.../routes/users.js:65:10) var User = require('../models/user'); passport.use(new LocalStrategy( function(username, ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

In React-router-dom version 5, match.params.id functions properly, but it experiences issues in version 6

Can anyone help me figure out the proper way to achieve this functionality in react-router version 6? When I use console.log with match, it returns undefined, even though it works fine in v5. import React from 'react' const NotePage = ({ match } ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

Get the object method within an AJAX success callback

Is there a way for me to access the FileUploader.prototype.saveImage() method in my code? Here is an example snippet: function FileUploader(object) { this.checkInputs(object); if (this.isImageSelected()) { this.beforeInit(object); ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Is there a way to prevent all attribute menu items within a ul/li List from being clicked when one of them has already been selected

When I quickly click on the Photos1, Photos2, Photos3, and Photos4 menus, the "$.get(..." is sent to the server four times. It's important that all of these menus are disabled after any one is clicked. My development environment includes NodeJS, Expre ...

Comparing two Objects in JavaScript results in automatic updates for the second Object when changes are made to the first

Can someone please assist me with a hash map issue I'm encountering in my for loop? When resetting the second object, it unintentionally alters the Map values of the previous Key in the Hash Map. Any guidance on how to prevent this behavior would be g ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

Encountered a glitch while trying to deploy a MERN stack project on Heroku

https://i.stack.imgur.com/HbIa0.png My project structure is as follows: Backend/ frontend/ Procfile package-lock.json package.json When I try to use post build for the React app in the package.json file of the backend, I encounter an error that says it ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...