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

});
相关推荐
檀越剑指大厂1 分钟前
【Linux系列】如何在 Linux 服务器上快速获取公网
linux·服务器·php
共享家95273 分钟前
linux-高级IO(上)
java·linux·服务器
xianxin_4 分钟前
CSS Outline(轮廓)
前端
moyu844 分钟前
遮罩层设计与实现指南
前端
Sammyyyyy10 分钟前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
timeweaver19 分钟前
深度解析 Nginx 前端 location 配置与优先级:你真的用对了吗?
前端·nginx·前端工程化
鲸落落丶20 分钟前
网络通信---Axios
前端
wwy_frontend22 分钟前
React性能优化实战:从卡顿到丝滑的8个技巧
前端·react.js
小高00737 分钟前
面试官:npm run build 到底干了什么?从 package.json 到 dist 的 7 步拆解
前端·javascript·vue.js
天选打工圣体38 分钟前
个人学习笔记总结(四)抽离elpis并发布npm包
前端