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.