Unable to perform the GET request method due to data indicating [object object]

Currently, I am attempting to use a get request method within both Vue and Express in order to retrieve data based on my v-model.

Displayed below is the code where I am trying to send the data to Express.

getResult() {
  axios
    .get(
      `${process.env.VUE_APP_API}/hospita/result/` +
        {
          hosp_name: "SAMPLE"
        }
    )
    .then(res => console.log(res.data))
    .catch(err => console.log(err));
}

Furthermore, here is the get request method responsible for receiving data from Vue.js.

router.get('/result/', (req, res) => {
    const sql = "SELECT * FROM ND_HOSP WHERE hosp_ptype = 'h' AND hosp_name LIKE ?";
    console.log(req.body)
    myDB.query(sql, ['%' + req.body.hosp_name + '%'], (err, result) => {
        if (err) {
            console.log(err)
        } else {
            try {
                res.send(result);
                /*  console.log(result) */
            } catch (err) {
                res.send(err)
            }
        }
    })
})

Despite these efforts, an error message appears stating http://localhost:9002/hospita/result/[object%20Object]

Answer №1

For your getResult() function, consider changing the method to post and replacing + with , when passing data in the body. Here is an example of how you can modify your code:

getResult() {
  axios
    .post( // <= change method to post
      `${process.env.VUE_APP_API}/hospita/result/`, // change `+` with `,`
        {
          hosp_name: "SAMPLE"
        }
    )
    .then(res => console.log(res.data))
    .catch(err => console.log(err));
}

Additionally, remember to update your router's method from get to post. Take a look at this code snippet for reference:

// change method `get` to `post`
router.post('/result/', (req, res) => {
  const sql = "SELECT *  FROM \
  ND_HOSP WHERE hosp_ptype = 'h' AND hosp_name LIKE ?";
  console.log(req.body)
  myDB.query(sql, ['%' + req.body.hosp_name + '%'], (err, result) => {
      if (err) {
          res.send(err)
      } else {
        res.send(result);
      }
  })
})

Don't forget, since we are using req.body, make sure to include body parser in your server.js or app.js. The implementation should resemble the following code:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

I trust this information will assist you in resolving any issues.

Answer №2

The issue lies in this line of code: res.send(result);

Result does not contain JSON data, instead it may contain any other object or an empty object like {}.

To troubleshoot, start by checking the content of result using console.log().

In cases like these, two functions can be very helpful:

JSON.stringify(object);
JSON.parse(strobj);

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

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

Unspecified binding in knockout.js

As a newcomer to JS app development, I am currently focused on studying existing code and attempting to replicate it while playing around with variable names to test my understanding. I have been working on this JS quiz code built with KO.js... Here is my ...

Submit JSON data that is not empty in the form of a custom format within the query string

Attempting to transmit JSON data using a GET request. JSON data: var data = { country: { name: "name", code: 1 }, department: {}, cars: ["bmw", "ferrari"], books: [] } Code for sending: var posting = $.ajax({ ur ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...

Exploring SubjectBehavior within my UserService and Profile Component

Within my ShareService, I have the following code snippet: isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); <==== default value is false CheckUser = this.isLogin$.asObservable(); public isLogin (bool){ ...

Removing elements in AngularJS using ngRepeat

Many have questioned how to implement item removal within the ngRepeat directive. Through my research, I discovered that it involves using ngClick to trigger a removal function with the item's $index. However, I haven't been able to find an exam ...

Expressing the assignment of arrays inside the req.body object to separate variables

I've been facing some challenges trying to get Express and body-parser to properly interpret the JSON object sent from the Angular side of my app. It seems like there might be an issue with how I'm assigning variables in my syntax. Despite trying ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

Angular is unable to POST to Rails server with the content-type set as application/json

Currently, I am attempting to send a POST request with Content-Type: application/json from Angular to my Rails backend. However, an error is being displayed in the console: angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found ...

struggling to send JSON data to PHP using AJAX

Here is the code snippet I am currently using. Javascript <script type="text/javascript"> var items = new Object(); items[0] = {'id':'0','value':'no','type':'img','filenam ...

Utilizing Electron's <webview> feature to display push notification count in the title

I'm currently working on a Windows app using Electron's webViewTag to integrate WhatsApp Web. While I have successfully implemented desktop toast notifications, I am curious if it is possible to display a notification count in the title bar of my ...

Concealing table columns using JavaScript - adapt layout on the fly

I am currently implementing a responsive design feature on my website, where I need to hide certain columns of a table when the viewport size decreases beyond a specific point. Initially, I tried using .style.visibility = "collapse" for all <tr> elem ...

personalize auto-suggestions in AngularJS

Here is a link to a custom search implementation using autocomplete in angularjs. Is it possible to modify this so that the matching starts from the first character? HTML <div ng-app='MyModule'> <div ng-controller='DefaultCtrl& ...

Leverage the power of Azure Redis Cache to efficiently store Node JS express

I recently attempted to create an Express 4 Web App using Azure. I came across multiple articles that suggested using Azure Redis Cache for storing sessions. However, I am unsure about the proper way to connect my web app to the redis cache. var session = ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...

The value of Vue's v-model data is currently undefined, likely due to an

When working with Vue 2, I encountered a scenario where I had data coming in from an ajax call. Here is the code snippet that exemplifies this: <template> <div> <input type="input" class="form-control" v-model="siteInfo.siteId"& ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

Guide on how to incorporate an external javascript file into an HTML button

I am currently working on an exercise through Udacity that involves creating an HTML form with JavaScript functions. The task is to input text into the form, submit it, and have it displayed on the webpage within a blue square. This exercise is designed to ...