【问题标题】:Read/Import a Post Request body from a json file in Node.js从 Node.js 中的 json 文件读取/导入 Post Request 正文
【发布时间】:2022-11-17 05:27:39
【问题描述】:

我有一个名为 data.json 的 json 文件,我希望它的内容成为 postData 函数中的 POST 请求的主体。

我如何读取内容或将内容作为我在 nodeJS 中的 const body 变量的值?

数据.json

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

索引.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();

【问题讨论】:

    标签: javascript node.js rest axios


    【解决方案1】:

    在你的情况下, then-catch :

    import file from "./your-path-file"
    // OR
    const file = require("./your-path-file");
    
    function postData() {
      const body = file;
      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!");
            const data = response.json(); // Get the data (response) from the request 
            console.log(data); // log the data - and you can assign it to variable, and use it.
          }
        })
        .catch((e) => {
          console.error(e);
        });
    

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      相关资源
      最近更新 更多