在Node.js中传递JSON数据是非常常见的操作,通常用于前后端交互、API数据交换等场景。以下是关于在Node.js中传递JSON数据的完整解答:
在Node.js中传递JSON数据主要涉及以下几种类型:
const data = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(data);
console.log(jsonString); // 输出: {"name":"John","age":30,"city":"New York"}
const jsonString = '{"name":"John","age":30,"city":"New York"}';
const data = JSON.parse(jsonString);
console.log(data.name); // 输出: John
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/api/data' && req.method === 'GET') {
const data = {
message: "Hello, World!",
timestamp: new Date()
};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
const data = {
name: "John",
birthDate: new Date()
};
// 序列化前转换Date对象
data.birthDate = data.birthDate.toISOString();
const jsonString = JSON.stringify(data);
console.log(jsonString); // 输出: {"name":"John","birthDate":"2023-10-05T12:34:56.789Z"}
// 反序列化后转换回Date对象
const parsedData = JSON.parse(jsonString);
parsedData.birthDate = new Date(parsedData.birthDate);
console.log(parsedData.birthDate); // 输出: Thu Oct 05 2023 12:34:56 GMT+0000 (Coordinated Universal Time)
通过以上内容,你应该能够在Node.js中正确地传递和处理JSON数据。如果有更多具体问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云