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");

});
相关推荐
None32114 小时前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
GIS之路14 小时前
ArcGIS Pro 中的 Python 入门
前端
树獭非懒14 小时前
告别繁琐多端开发:DivKit 带你玩转 Server-Driven UI!
android·前端·人工智能
兆子龙15 小时前
当「多应用共享组件」成了刚需:我们从需求到模块联邦的落地小史
前端·架构
Qinana15 小时前
从代码到智能体:MCP 协议如何重塑 AI Agent 的边界
前端·javascript·mcp
Wect15 小时前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
不会敲代码115 小时前
从入门到进阶:手写React自定义Hooks,让你的组件更简洁
前端·react.js
用户54330814419415 小时前
拆完 Upwork 前端我沉默了:你天天卷的那些技术,人家根本没用
前端
洋洋技术笔记15 小时前
Vue实例与数据绑定
前端·vue.js
Marshall15115 小时前
zzy-scroll-timer:一个跨框架的滚动定时器插件
前端·javascript