Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server?. Here is a snippet of my controller code:

var app = angular.module('myApp',[]);
app.controller('myCtrl',function ($scope, $http){
  $scope.saveImage = function(){
    var data = JSON.stringify(canvas);
    debugger;
    $http({
      url: 'http://localhost:8080',
      method: "POST",
      data: data,
      header: 'Content-Type: application/json'
    });
  }
});

Although the developer tools indicate that the JSON string "data" has been successfully created with content in the frontend controller, when passed to the Node backend, I am unable to retrieve anything from req.body. Here is the relevant backend code snippet:

// set up
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: false}));
var saveCount = 1;
//functions
// application -------------------------------------------------------------
app.use(express.static('./public'));

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.post('/', function (req, res) {
  fs.writeFile(__dirname+"/save/post"+saveCount.toString()+".json", req.body, function(err) {
    if(err) {
       return console.log(err);
    }
    res.send('The file was saved!');
  }); 
  saveCount++;
});

//listen
app.listen(8080, function () {
  console.log('Example app listening on port 8080!');
});

Upon reviewing my post.json files, I consistently find that they only contain [object Object]. This behavior leaves me perplexed as to what might be causing this issue.

Answer №1

Here are a few important points to consider:

  1. Avoid unnecessary use of JSON.stringify() on your data object when passing it to $http.
  2. Make sure to use bodyParser.json() instead of bodyParser.urlencoded().
  3. Remember to call JSON.stringify() before writing to your file.

Your code should resemble the following:

var app = angular.module('myApp',[]);
app.controller('myCtrl',function ($scope, $http){
  $scope.saveImage = function(){
    debugger;  // What is the purpose of this?
    $http({
      url: 'http://localhost:8080',
      method: "POST",
      data: canvas,
      header: 'Content-Type: application/json'
    });
  }
});

Additionally,

// set up
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require("body-parser");
app.use(bodyParser.json());
var saveCount = 1;
//functions
// application -------------------------------------------------------------
app.use(express.static('./public'));

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.post('/', function (req, res) {
  fs.writeFile(__dirname+"/save/post"+saveCount.toString()+".json", JSON.stringify(req.body), function(err) {
    if(err) {
       return console.log(err);
    }
    res.send('The file was saved!');
  }); 
  saveCount++;
});

//listen
app.listen(8080, function () {
  console.log('Example app listening on port 8080!');
});

The appearance of [object Object] indicates that your object successfully reaches the server and processed correctly. It is not necessary to stringify on the frontend as $http can handle object transmission efficiently. Ensure that bodyParser parses the post data as a JSON object with the .json() method for proper handling. Alternatively, you can modify the Content-Type to application/text to prevent object parsing on the server side.

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

Remove any nulls or undefined values from the object

I have developed a custom function that eliminates null and undefined values from an object. However, it seems to be mistakenly removing keys where the value is 0 as well. For instance: { key1: 'value1', key2: 0 } Even though it shouldn&ap ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

Utilizing lazy loading in Angular with 2 modules that require sharing the same service

Custom Module Integration: export class CustomModule { static forRoot(): ModuleWithProviders { return { ngModule: CustomModule, providers: [ MyService ] }; } } Dynamic Module #1: @NgModule({ imports: [ CommonM ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

Issues with installing dependencies in Angular 2 through npm

While developing my Angular 2 application locally, everything was working smoothly. However, when I tried to deploy it to the server without the node_module folder and then did a npm install followed by a build, my app just kept showing "Loading..." withou ...

Angular JS causing text alignment issues in table cells when viewed on mobile devices

I have created a web application that requires both desktop and mobile views, utilizing Angular JS. Everything is functioning as expected except for the text alignment within tables. I attempted using <td align="left">, but it did not produce any cha ...

What makes a function and a callback asynchronous in Node.JS?

When delving into Node.js, many newcomers understand that transforming synchronous or in-line code to utilize functions/callbacks can prevent their code from being blocked. The question arises regarding the functioning of the event stack within this contex ...

Is it possible to retrieve calculated data from a child component and pass it to the parent component?

Is there a way to transfer computed data from a child component to a parent component? Currently, I am passing data from the parent to the child first and then I would like to utilize the computed property (data) in the parent component. This is crucial as ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

Exploring the Possibilities of Nipplejs Integration in Vue with Quasar

Trying to implement Nipplejs in my Vue Project using quasar Components. Installed nipplejs through npm install nipplejs --save. Attempted integration of the nipple with the code snippet below: <template> <div id="joystick_zone">&l ...

Tips for querying Mongo using Node.js

Although this question may seem repetitive, please bear with me. My goal is to query MongoDB directly from the dom eventually, but for now, I'm working on querying from my routes module. Below is my query: var db = require('./config/db.js&apos ...

The RedirectToAction function is malfunctioning within the ActionResult implementation

public ActionResult SaveUploadedFile(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { try { string path = Path.Combine(Server.MapPath("~/Images"), ...

Combining Laravel and VueJs for a Multi-Page Application (MPA)

I have recently developed a website using a combination of Laravel and VueJs. However, I am facing some confusion regarding the most suitable routing architecture to implement. Currently, my application has the following setup: The routing system is man ...

What are the steps for including and excluding components in Parallax JS?

When working with Parallax JS: I am trying to modify the components within the <li> tags of my menu, but I am unsure how to do so without restarting the plugin. I cannot seem to find the destroy command. Currently, I am using the JQuery version of ...

Ways to identify a modification in ag-grid when there is an update in my row data while transitioning from one component to another

I am currently working on a project using angular6 implementing ag-grid to display data from an angular dialog box. With multiple teams contributing, each creating their own components, I have encountered a unique situation that I am struggling to resolv ...

Effortless integration of jQuery with Google Maps autocomplete feature

I've successfully implemented Google Maps Autocomplete on multiple input tags like the one below: <input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" /> To enable Google Maps au ...

Setting the Node.js version in Eclipse on a Windows operating system can be easily accomplished by following these

After attempting to execute "ng serve" within Eclipse, an error message is displayed: The error states that you are currently using Node.js version v6.9.4, which is not compatible with Angular CLI 8.0+. To successfully use Angular CLI, you need to have No ...

Is it feasible to retrieve information within a behavior in Drupal?

I recently installed the "Autologout" Drupal module, which can be found at . This module includes a timer that ends your session if there is no activity on the page for a set period of time. However, I am interested in adjusting the timer value to better ...

Error encountered when attempting to retrieve HTML content from localhost using AJAX

Attempting to insert HTML code into a div element using ajax, similar to how it's done with an iframe. Testing this out locally first to avoid Same Origin Policy complications. The web application is currently hosted on a wamp server. There are two ...