Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading