Node 服务器数据响应类型处理

一、设置不同的响应数据类型

在 Node.js 的 `http` 模块中,通过 `res.writeHead` 方法可以设置不同的响应头,以指定响应的数据类型。

1. 纯文本响应

对于纯文本响应,可以将 `Content-Type` 设置为 `text/plain`

javascript 复制代码
const http = require("http");

const server = http.createServer((req, res) => {

  res.writeHead(200, { "Content-Type": "text/plain;charset=utf8;" });

  res.end("你好");

});

server.listen(3000, () => {

  console.log("Server running on port 3000");

});

2. HTML 响应

对于 HTML 响应,可以将 `Content-Type` 设置为 `text/html`:

javascript 复制代码
const http = require("http");

const server = http.createServer((req, res) => {

  res.writeHead(200, { "Content-Type": "text/html;charset=utf8;" });

  res.end("<h1>你好<h1>");

});

server.listen(3000, () => {

  console.log("Server running on port 3000");

});

3. JSON 响应

对于 JSON 响应,可以将 `Content-Type` 设置为 `application/json`:

javascript 复制代码
const http = require("http");

const server = http.createServer((req, res) => {

  const data = { message: "Hello, World!" };

  res.writeHead(200, { "Content-Type": "application/json" });

  res.end(JSON.stringify(data));

});

server.listen(3000, () => {

  console.log("Server running on port 3000");

});

4. 图片响应(以 JPEG 为例)

对于图片响应,需要将 `Content-Type` 设置为相应的图片类型,如 `image/jpeg`:

javascript 复制代码
const http = require("http");

const fs = require("fs");

const server = http.createServer((req, res) => {

  const imagePath = "path/to/your/image.jpg";

  fs.readFile(imagePath, (err, data) => {

    if (err) {

      res.writeHead(500, { "Content-Type": "text/plain" });

      res.end("Error loading image");

    } else {

      res.writeHead(200, { "Content-Type": "image/jpeg" });

      res.end(data);

    }

  });

});

server.listen(3000, () => {

  console.log("Server running on port 3000");

});

5. 二进制文件响应

对于二进制文件响应,可以根据文件类型设置相应的 `Content-Type`:

javascript 复制代码
const http = require("http");

const fs = require("fs");

const server = http.createServer((req, res) => {

  const binaryFilePath = "path/to/your/binaryfile.bin";

  fs.readFile(binaryFilePath, (err, data) => {

    if (err) {

      res.writeHead(500, { "Content-Type": "text/plain" });

      res.end("Error loading binary file");

    } else {

      res.writeHead(200, { "Content-Type": "application/octet-stream" });

      res.end(data);

    }

  });

});

server.listen(3000, () => {

  console.log("Server running on port 3000");

});
相关推荐
星辰云-12 分钟前
# Linux Centos系统硬盘分区扩容
linux·运维·centos·磁盘扩容
雪碧聊技术19 分钟前
深入解析Vue中v-model的双向绑定实现原理
前端·javascript·vue.js·v-model
快起来别睡了21 分钟前
手写 Ajax 与 Promise:从底层原理到实际应用
前端
Hellc00724 分钟前
Nginx 高级 CC 与 DDoS 防御策略指南
运维·nginx·ddos
feilieren39 分钟前
Docker 安装 Elasticsearch 9
运维·elasticsearch·docker·es
打不着的大喇叭1 小时前
uniapp的光标跟随和打字机效果
前端·javascript·uni-app
无我Code1 小时前
2025----前端个人年中总结
前端·年终总结·创业
程序猿阿伟1 小时前
《前端路由重构:解锁多语言交互的底层逻辑》
前端·重构
Sun_light2 小时前
6个你必须掌握的「React Hooks」实用技巧✨
前端·javascript·react.js
爱学习的茄子2 小时前
深度解析JavaScript中的call方法实现:从原理到手写实现的完整指南
前端·javascript·面试