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

});
相关推荐
Felicity_Gao3 小时前
uni-app VOD 与 COS 选型、开发笔记
前端·笔记·uni-app
我狸才不是赔钱货4 小时前
前端技术栈全景图:从HTML到现代框架的演进之路
前端·html
百花~5 小时前
前端三剑客之一 HTML~
前端·html
chinesegf5 小时前
Docker篇4-本地项目app.py与docker加载项目镜像的开发顺序
运维·docker·容器
CyreneSimon5 小时前
Docker 拉取配置教程:解决镜像拉取连接超时问题
运维·docker·容器
lang201509285 小时前
Spring远程调用与Web服务全解析
java·前端·spring
李子红了时6 小时前
【墨铺网教程】一台电脑加入多个局域网,让电脑做上传下载主力又当存储盘
运维·服务器·电脑
孤狼warrior7 小时前
爬虫进阶 JS逆向基础超详细,解锁加密数据
javascript·爬虫
Awkwardx7 小时前
Linux系统编程—线程同步与互斥
linux·服务器
前端炒粉7 小时前
18.矩阵置零(原地算法)
javascript·线性代数·算法·矩阵