Transmitting an Ajax request via property path

I'm experiencing issues with sending data to the server.

Here is my Ajax call:

$.ajax({
  url: config.api.url,
  type: config.api.method,
  contentType: config.api.contentType, 
  dataType: config.api.dataType,       
  data: config.api.dataType === 'GET' ? {} : JSON.parse(tmp),
  headers: config.api.headers,
  success: (response) => { onSuccess(response); },
  error: (error) => { onError(error); }
});

This is the data I am trying to send:

{
  sort: { name: 1 }
}
// The name property is set using sort['name'] = 1; in js

However, the server received it as:

{ 'sort[name]': 1 }

In my Node.js server code, I have:

exampleData = (req, res) => {
  var sort = req.body.sort;
  console.log(sort);       // undefined
  console.log(req.body);   // { ..., 'sort[name]': 1 }
}

When checking the Chrome Form Data, I noticed something unusual:

https://i.sstatic.net/KktAL.png

It seems like there is an issue with reading the object correctly. Any ideas on how to fix this?

Answer №1

If you are utilizing express.js, make sure to include the body-parser middleware for parsing incoming request bodies.

const app = require('express')(),
    bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', function (req, res) {
    console.log(req.body);
});

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

Enhancing the functionality of a bootstrap button with the addition of an

My goal is to have a button that opens a URL in a new tab. I've managed to achieve this using window.location.href, but it doesn't open the URL in a new tab. The code I'm working with is written in jQuery and Javascript, and it's part ...

Investigating Memory Usage in Google Maps API v3

I have been working on my project utilizing the Google Maps API v3, but I have encountered some significant memory leaks while browsing. Despite my efforts to find unload methods specifically for Gmap, I have not been successful. My website uses ajax, and ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Sending a post request with Ajax in an ASP.NET Webforms application

When attempting to post data to the server using an AJAX call, I encountered an error. var userDetails = {}; userDetails["Name"] = "Saran"; var DTO = { 'userDetails': userDetails }; $.ajax({ type: "POST", contentTyp ...

Sophisticated jQuery templates

Working with jQuery templates can be straightforward for basic data structures. <script type="jquery/x-jquery-tmpl" id="myTemplate"> <li> ${Element} </li> </script> var elements = [ { Element: "Hydrogen" }, { Element: "Oxy ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

I am unable to find any resolution, so to speak

Despite reading numerous posts and trying different examples on my own, I still can't grasp this particular question that has been asked many times before. My struggle lies in returning images from various folders and processing them individually in a ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

"Implementing the Three.js OBJloader feature with the enhanced functionality of

I'm looking to create a simple 3D model viewer with rotation capabilities, but I've run into an issue. When I add OrbitControls to my code, the page just shows up as blank: controls = new THREE.OrbitControls( camera ); controls.addEventListener( ...

sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays? Below is an example to help explain the process. To filter the data, use startnumber and endnumber in the query. const data = [ { "name": "x", "points": [ [100, 50, 1], //[number, value ...

"Enabling image uploads in Vue.js with TinyMCE: A step-by-step guide

I have integrated tinymce into my Vue.js application, but I am experiencing issues with uploading images. I have included the following package in my project: import Editor from '@tinymce/tinymce-vue'. I believe I might be missing a necessary pl ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

Locate items visible to the user on the display

I need to find a way to access the products that are currently visible when a user scrolls through my product list. Each product in the list has the class name product. <div class="product"> <span>price:2</span> </div> ...

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. https://i.sstatic.net/ZR0IY.png The PHP script should disp ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

What is the best way to utilize both doPost() and doGet() requests in a single servlet while incorporating ajax technology?

Currently working on a small project involving JSP servlets. I need a practical example demonstrating the implementation of both the doGet() and doPost() methods within the same servlet, while handling AJAX calls within a JSP form. Additionally, could you ...

What is the method of aligning content to the left side in a slick slider?

My slider is set up to display three elements, but I'm having trouble aligning one or two elements to the left instead of centering them. jQuery(function () { jQuery('.slider-blog').slick({ arrows: false, dots: true, ...