Home > Net >  Read/Import a Post Request body from a json file in Node.js
Read/Import a Post Request body from a json file in Node.js

Time:11-17

I have a json file called data.json and I want its content to be the body of a POST request in the postData function.

How can I read the content or get the content to be the value of my const body variable in nodeJS?

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

CodePudding user response:

in your case, 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);
    });
  • Related