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

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

The ng-repeat function is not functioning properly when used within an li element to trigger

I have utilized the Dialog service to create a pop-up window. My intention is to display a message to the user in this format: txt = '<ul> <li data-ng-repeat = "eachValue in dummnyList" > {{eachValue | applyFilte ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Exploring the foundations of web development with html and stylus

If you have experience with the roots platform, you are familiar with its default stack including jade, stylus, and coffee script. The documentation provides some information on using HTML, CSS, and pure JavaScript instead of the compiled languages, but d ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use var viewModel = this; employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functio ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

Error: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON." const functions = require("firebase-functions"); const axios = ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

Button ng-click with identical function parameters

I am facing an issue with two buttons that have the same ng-click but different parameters. <label class="item item-input"> <button ng-click="takePicture(true)">Save Settings</button> <button ng-click="takePicture(false)">Choos ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...