Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它允许开发者使用 JavaScript 来编写服务器端的应用程序。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
Node.js:
JSON:
{}
包围。[]
包围。以下是一个简单的 Node.js 服务器示例,它接收 JSON 数据并将其返回:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/data') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = JSON.parse(body);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
} catch (error) {
res.statusCode = 400;
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
问题:
解决方法:
try...catch
语句捕获可能的异常。示例代码:
try {
const data = JSON.parse(body);
} catch (error) {
console.error('JSON parsing error:', error);
res.statusCode = 400;
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
通过这种方式,可以优雅地处理 JSON 解析错误,并向客户端返回有意义的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云