Trying to parse JSON Object from POST Request in Express v4 using body-parser

别来无恙 提交于 2021-01-28 05:29:33

问题


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.


回答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");




回答2:


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");


来源:https://stackoverflow.com/questions/44378391/trying-to-parse-json-object-from-post-request-in-express-v4-using-body-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!