在Web开发中,response
对象通常与HTTP响应相关联,它包含了服务器发送给客户端的所有信息。当你在服务器端执行JavaScript代码时,response
对象用于将数据发送回客户端。以下是一些基础概念和相关信息:
response
对象允许你设置这些部分的内容。以下是一个简单的Node.js服务器示例,展示了如何使用response
对象发送不同类型的响应:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/text') {
// 发送文本响应
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
} else if (req.url === '/json') {
// 发送JSON响应
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello, JSON!' }));
} else if (req.url === '/html') {
// 发送HTML响应
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello, HTML!</h1>');
} else {
// 处理未知路径
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Content-Type
头。通过理解这些基础概念和实践技巧,你可以更有效地处理Web应用中的response
对象,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云