尝试使用body-parser从Express v4中的POST请求解析JSON对象 [英] Trying to parse JSON Object from POST Request in Express v4 using body-parser

查看:78
本文介绍了尝试使用body-parser从Express v4中的POST请求解析JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在自学更多有关服务器代码的知识,特别是使用Node.js和Express,并且在接收和解析从POST请求发送的JSON对象时遇到很多麻烦.我看了无数其他文章(链接到下面),我无法弄清到底是怎么回事.这是我看过的东西:

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:使用AJAX发送JSON对象 JavaScript:使用Ajax发送JSON对象吗?如何在Express应用程序中使用JSON POST数据如何使用JSON POST数据在Express应用程序中使用XMLHttpRequest发送POST数据使用XMLHttpRequest发送POST数据如何在Node.js中提取POST数据?如何在Node.js中提取POST数据?

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:

发送POST请求

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

处理服务器中的POST请求

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

每当我尝试打印"req.body"的内容时,我都会得到"[object Object]"的输出.有什么想法吗?

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

我的问题已经解决.我已经改变了

My issue has been solved. I have changed

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

收件人

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

我还将POST XMLHTTPRequest中的Content-Type更改为"application/json",以帮助格式化.

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

推荐答案

"[对象对象]" 是JavaScript隐式 toString 操作的默认结果,它使用尝试将该对象的字符串表示形式写入文件时.

"[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.

尝试将 JSON.stringify(req.data)写入文件.

此外,在客户端–考虑更改您的 Content-Type 标头以匹配:

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

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

这篇关于尝试使用body-parser从Express v4中的POST请求解析JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆