1

I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:

Javascript: Send JSON Object with AJAX Javascript : Send JSON Object with Ajax? How do I consume the JSON POST data in an Express application How do I consume the JSON POST data in an Express application Send POST data using XMLHttpRequest Send POST data using XMLHttpRequest How do you extract POST data in Node.js? How do you extract POST data in Node.js?

All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:

Send POST Request

var button = document.querySelector("#button");

button.onclick = function(){
    console.log("Getting data from local server");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/data/test.json", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};

Handle POST Request In Server

var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");

var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));

//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
    res.send("Submitted GET Request");
})

//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
    console.info("Submitting POST Request to Server");
    console.info("Request body: " + req.body);
    //write the file
    fs.writeFile(__dirname + "/../client/data/test.json", req.body, 
    function(err){
        if(err){
            console.error(err); //print out the error in case there is one
            return res.status(500).json(err);
        }

        //resolve the request with the client
        console.info("updated test.json");
        res.send();
    });
})

//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);

Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?

EDIT: My issue has been solved. I have changed

console.info("Request body: " + req.body);

To

console.info("Request body: " + JSON.stringify(req.body));

I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.

Noah Kellem
  • 35
  • 1
  • 6
  • 2
    uh... your content type doesn't match your data... ??? – Kevin B Jun 05 '17 at 22:04
  • 1
    Try this JSON.stringify(req.body); – VivekN Jun 05 '17 at 22:05
  • [object object] means that the variable you are trying to print isn't a string, easy fix just use JSON.stringify(req.body); – Ian Wise Jun 05 '17 at 22:12
  • @KevinB I thought I could use "application/json" and "application/x-www-form-urlencoded" interchangeably based on looking at different posts, but this was definitely a part of the issue. – Noah Kellem Jun 05 '17 at 23:17

2 Answers2

1

"[object Object]" is the default result of JavaScript's implicit toString operation, which it uses when trying to write a string representation of that object to the file.

Try writing JSON.stringify(req.data) to the file instead.

Also, on the client side – consider changing your Content-Type header to match:

xhr.setRequestHeader("Content-Type", "application/json");

nikulis
  • 124
  • 6
0

If your post body is expected to be JSON, then change this line

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

To

 xhr.setRequestHeader("Content-Type", "application/json");
Gonras Karols
  • 1,150
  • 10
  • 30