Attempting to transmit a layered JSON data structure via an HTTP 'POST' request using Javascript

My current challenge involves attempting to send an array of JSON objects to a local server using an HTTP 'POST' request. I've been utilizing an npm module from here to handle the request. While my code has generally worked fine in the past, I am now facing an unresolved issue.

var request = require('request');
const obj = require('./bugs.json');

obj.forEach(element => {
    // Set the headers
  var headers = {
    'Content-Type': "stuff",
    'x-authorization': "stuff"
  }

  // Configure the request
  var options = {
      url: 'http://localhost:8080/bugreport/import',
      method: 'POST',
      headers: headers,
      form: {
          'subject': element.subject,
          'description': element.description,
          'platform': element.platform,
          'date': element.date,
          'author': element.author,
          'isSolved': element.isSolved,
          'createdAt': element.createdAt,
          'updatedAt': element.updatedAt,
          'id': element.id
      }  
  }
//
  // Start the request
  request(options, function(error, response, body){
      if (!error && response.statusCode == 200) {
          console.log("No error detected.");
          console.log(body)
      }
      else {
          console.log("Error: " + error);
      }
  })

});

The specific line causing issues is 'author': element.author,. All other attributes are basic data types, but author itself is a nested JSON. The structure of the JSON file is as follows:

[
    {
    "subject": "Bug",
    "description": "Testing brscript",
    "platform": "A",
    "date": "2/15/2018",
    "author": [
        {
            "username": "testuser1",
            "firstName": "test",
            "lastName": "user1",
            "password": "password",
            "admin": false,
            "isVisible": true,
            "isDeleted": false,
            "createdAt": "2018-02-08T18:42:58.473Z",
            "updatedAt": "2018-02-13T15:51:17.954Z",
            "id": 170
        }
    ],
    "isSolved": false,
    "createdAt": "2/15/2018",
    "updatedAt": "2/15/2018",
    "id": 999
    }
]

I have prior experience with similar tasks, but not with a nested JSON as part of the data. Every attribute except for the author JSON successfully sends. There seems to be an issue with how I'm handling the syntax related to the nested JSON. Various attempts to resolve this have proven unsuccessful.

Answer №1

experiment with JSON.stringify(body) inside your console.log()

additionally, include application/json in the Content-Type header

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

How can I filter an array by a nested property using Angular?

I need help with objects that have the following format: id: 1, name: MyObj properties: { owners: [ { name:owner1, location: loc1 }, { name:owner2, location: loc1 } ] } Each object can have a different number of owners. I' ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

Transition the background image into view upon hover

I'm looking to enhance my jQuery code that changes the background image when hovering over text by adding a fade-in effect. Here's the current code I have: $(document).ready(function(){ $("#anatomyNow").hover(function(){ $("#bg").cs ...

JsonConverting, JObjecting, JPropertying

I have a code snippet here that generates NewtonSoft Jobjects JObject o = new JObject(new JProperty("DataSources", new JArray(from p in repDatasource.DataSources select JObject( JProperty("Columns", new JArray (from q in p.columns select new JObject(new J ...

unable to form the directory named tns_modules

Facing an issue while trying to run the demo application in Nativescript. Performed the following command: tns run ios Encountered an error: Unable to apply changes on device: DEVICE_ID. Error is: Processing node_modules failed. Error: cp: cannot c ...

Ensure that the function is invoked only a single time, whether it be in the componentDidMount or componentDidUpdate lifecycle

I need to ensure that a function is executed only once based on certain props and state conditions. class MyComponent extends Component { state = { externalInfoPresent: false, infoSaved: false, } async componentDidMount() { await this.p ...

Trouble arises when attempting to use JavaScript, JSP, and JSON in conjunction with

I am in the process of creating a client-server application where I send a request from the client to the server using a JSON object for registration. However, despite receiving a JSON response with an "OK" field as expected, the client keeps triggering th ...

What is preventing me from downgrading Rxjs?

Looking for a solution to downgrade my rxjs package from version 6.1.0 to 5.5.4. Here's what I've tried so far: npm -v rxjs 6.1.0 npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73010b190033465d465d47"> ...

Substituting the parameter 'props' with variable names does not function properly in Reactjs functional syntax when using webpack 1

I'm currently working through a tutorial on ReactJs from Lynda that is based on Webpack 1. After making the following changes: import 'path/to/style.scss' export const MyValues = (props) => ( <div className="values"> <di ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Separate scales for small multiple line charts

Explore the notebook here. I am currently developing a small multiple line chart using d3.v5 on Observable, with the dataset organized as follows: https://i.sstatic.net/QQblnm.png When visualizing, the y scale utilizes the num values from the values arr ...

The variable in list comprehension is being referenced before being assigned

I'm currently working on creating a list using this JSON file: city_list = [ city for city in metroextractor_cities['regions'][region]['cities'] for region in metroextractor_cities['regions']] When running t ...

Finding the measurement of a sofa using couch.get(data, headers, status)

After attempting to set up a node.js application with express.js by connecting to couchdb, I utilized the npm package called nodejs-couch. app.get('/', function(req, res) { couch .get(dbName, viewUrl) .then( function(data, heade ...

Leveraging the HTTP Client in golang to interact with the Places API, parsing JSON data and handling invalid characters

Just started learning Go and decided to test the Google Places API. I am struggling with writing the request as it goes through but I cannot Unmarshall the response. Would really appreciate some guidance on how to print the JSON in string form for decodi ...

Unable to recognize click event within the ng-click function

I need to identify when a click event occurs on an SVG element, specifically on a g element within the SVG element. Currently, I have created this JSFiddle The ng-click function is working properly, but unfortunately, the click event is not being detecte ...

Displaying a variable in a live HTML user interface

I have successfully created a Python program that captures data from an Arduino Potentiometer and shows it on the Python console. Now, I am working on enhancing the output by displaying it in a local HTML file. I am seeking guidance on how to incorporate t ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

I require assistance with formatting a JSON file

Can someone assist me in converting the json format from the following: {"aaData":[["<\/i><\/a> \r\n <\/i><\/a>",["00404","smith","20000000.00","75000.00","0.00","0.00","0.00","0.00","0.00","0.00","0. ...

Developing a Meteor application with the powerful combination of Vue.js and Typescript

I'm struggling to implement Typescript in a Meteor project with Vue. Here are the commands I used to create a project from scratch: Commands meteor create --vue gift-list-app meteor add typescript meteor npm install --save-dev @types/meteor meteor a ...