将整个请求体作为JSON对象发送到响应中

huangapple go评论57阅读模式
英文:

Sending Entire Req Body as JSON object in response

问题

我正在学习NodeJs,目前我刚刚制作了一个中间件函数,该函数将整个req对象作为json对象中的一个键值对的值发送(我知道这很长),但只是为了学习目的,我这样做了。

现在我知道req本身是一个对象,其值必须是一个字符串,所以我尝试将其转换:

这是我的代码

function prod (req, res) {
    console.log("This is a body of Req :- ", req);
 
    // const x = JSON.stringify(req);            // 方法1  // 抛出“TypeError: Converting circular structure to JSON”错误
    
   // const  x = String(req)                   // 方法2  // 显示[object object]  
  
   // const  x = req.toString()                 // 方法3   // 显示[object object] 

    res.status(200).json({"Request": `${x}`});
}
module.exports = prod

现在我按照顺序尝试了这3种方法,但都没有得到期望的结果。
方法1显示“TypeError: Converting circular structure to JSON”,而其他两种方法将其显示为“[object object]”。
然而,在console.log()行中,整个req正确打印出来。请问有人能告诉我为什么在“响应”中不会发生这种情况,还有如何将整个req发送到“res”的json主体中?

英文:

I am learning NodeJs , currently I have just made a middleware function which will send the entire
req object as value of a single key-value pair in json object (I know it is very long ) , but just for learning purpose I did it.

Now I know that req is a object in itself and the value must be a string , so I tried to convert it :-

This is my code

function prod (req, res) {
    console.log("This is a body of Req :- " , req );
 
    // const x = JSON.stringify(req);            // Method 1  // throws error of TypeError: Converting circular structure to JSON
    
   // const  x = String(req)                   // Method 2  // displays [object object]  
  
   // const  x = req.toString()                 // Method 3   // displays [object object] 

    res.status(200).json({"Request": `${x}`});
}
module.exports = prod

Now I tried these 3 methods as mentioned one by one, but none of them gave desired result.
Method 1 shows TypeError: Converting circular structure to JSON whereas other 2 methods displays it as [object object].
However in the console.log() line , entire req is printed porperly. Can anyone please tell me why is it not happening in the response & also how can I send the entire req in json body of res

答案1

得分: 2

Express中的请求和响应对象不是简单的JSON对象,而是带有不可序列化方法的类。因此会出现“将循环结构转换为JSON”错误。

你可能需要的变量是req.body,所以不要对请求本身进行字符串化,尝试使用JSON.stringify(req.body)。这样应该就可以了。

还要记住,通常HTTP GET请求没有附加的消息体,所以如果你构建的路由是用于GET请求,它的消息体可能会是“undefined”。

英文:

The request and response objects in Express aren’t simple JSON objects like you expect; they’re classes with methods that aren’t serializable. Hence the “converting cyclical structure to JSON” error.

The variable you’re looking for is probably req.body, so instead of stringifying the request itself, try JSON.stringify(req.body). That should do the trick.

Also keep in mind that HTTP GET requests don’t have bodies attached typically, so if the route you’re building is for a GET request it may come out as “undefined”.

答案2

得分: 1

Express.js express.json() 函数

express.json() 函数是Express中的一个内置中间件函数。它用于解析带有JSON数据的传入请求,并基于body-parser

语法:

express.json([options])

您也可以使用 app.use(express.json()); 这种方式。它会将请求中的数据解析为JSON格式。

示例

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

app.post('/', function (req, res) {
    console.log(req.body.name);
    res.end();
})

app.listen(PORT, function (err) {
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});
英文:

Express.js express.json() Function

The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Syntax:

express.json( [options] )

You can also use app.use(express.json());
It is convert req.body values in json formate

Example

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

app.post('/', function (req, res) {
console.log(req.body.name)
res.end();
})

app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

huangapple
  • 本文由 发表于 2023年4月4日 12:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定