You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何读取JSON文件作为POST请求的请求体?

在Node.js中读取JSON文件作为POST请求体的方法

你需要读取data.json文件内容,将其作为postData函数里POST请求的请求体赋值给const body变量,以下是具体实现方案:

现有文件内容

data.json

{"name":"John", "age":30, "car":null}

原index.js代码

function postData() {
  const body = [];
  const headers = {
    "Content-type": "application/json",
  };
  axios
    .post(`${BASE_URL}/data`, body, { headers })
    .then((response) => {
      if (response.status === 200) {
        console.log("Your Data has been saved!");
      }
    })
    .catch((e) => {
      console.error(e);
    });
}
postData();

解决方案

Node.js提供fs模块用于文件操作,下面提供两种常用实现方式:

方法1:同步读取(fs.readFileSync)

适合简单场景,同步读取会阻塞后续代码直到文件读取完成:

const fs = require('fs');
const path = require('path');
const axios = require('axios');
// 替换为你的实际API地址
const BASE_URL = 'https://your-api-domain.com';

function postData() {
  // 拼接文件绝对路径,避免相对路径问题
  const filePath = path.join(__dirname, 'data.json');
  // 读取文件原始内容
  const rawData = fs.readFileSync(filePath, 'utf8');
  // 解析为JSON对象作为请求体
  const body = JSON.parse(rawData);

  const headers = {
    "Content-type": "application/json",
  };
  axios
    .post(`${BASE_URL}/data`, body, { headers })
    .then((response) => {
      if (response.status === 200) {
        console.log("数据已保存!");
      }
    })
    .catch((e) => {
      console.error("请求或文件读取失败:", e);
    });
}
postData();

方法2:异步非阻塞读取(fs.promises.readFile)

更符合Node.js异步编程模型,避免阻塞事件循环:

const fs = require('fs').promises;
const path = require('path');
const axios = require('axios');
const BASE_URL = 'https://your-api-domain.com';

// 使用async/await简化异步流程
async function postData() {
  try {
    const filePath = path.join(__dirname, 'data.json');
    const rawData = await fs.readFile(filePath, 'utf8');
    const body = JSON.parse(rawData);

    const headers = {
      "Content-type": "application/json",
    };
    const response = await axios.post(`${BASE_URL}/data`, body, { headers });
    if (response.status === 200) {
      console.log("数据已保存!");
    }
  } catch (e) {
    console.error("请求或文件读取失败:", e);
  }
}
postData();

关键注意点

  • 务必确保data.json路径正确,使用path.join(__dirname, 'data.json')可以避免因执行目录不同导致的路径错误
  • 若data.json内容格式不合法,JSON.parse会抛出异常,建议在catch块中统一处理文件读取、解析和请求的错误
  • 确保已安装axios:执行npm install axios,并在代码中正确引入

内容的提问来源于stack exchange,提问作者Didi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:10:31