I am trying to send a POST request but the server I am sending the request to says I sent an empty object {}, I console.log(data) in my nodejs application and I can see the object is not empty, why is that?
import axios from "axios";
import { readFileSync, createReadStream } from "fs";
import FormData from "form-data";
import dotenv from "dotenv";
dotenv.config();
console.log("Parsing JSON data 💾");
const jsonData = readFileSync("data/data.json").toString();
const products: any[] = JSON.parse(jsonData).products;
console.log("Products Store in JavaScript Object 🛒");
products.forEach((product: any, index: number) => {
console.log(
`Creating Product ${index + 1}/${products.length} - ${product.name}`
);
let data = new FormData();
let dataObj: any = {};
for (const [key, value] of Object.entries<string>(product)) {
dataObj[key] = value;
if (key.includes("image")) {
data.append(key, createReadStream(value));
} else {
if (key === "variants") {
data.append(key, JSON.stringify(value));
} else {
data.append(key, value);
}
}
}
console.log(data);
axios
.post("http://localhost:8000/api/v1/product/create", data, {
headers: {
...data.getHeaders(),
Cookie: `access_token=${process.env.ACCESS_TOKEN}; csrftoken=${process.env.CSRF_TOKEN}`,
},
})
.then(() => {
console.log(`Product - ${product.name} Created ✔`);
})
.catch((err) => {
console.log(`Product - ${product.name} Failed to create ❌`);
if (err.response) {
console.log(err.response.data);
} else {
console.log("Internal server error");
}
});
});