0

I am using fetch to post data from react side to nodejs (both of which are running in my localhost) so what i am doing is

let formData = new FormData();
    formData.append("agent_name", this.state.agentName);
    formData.append("agent_email", this.state.agentEmail);
    formData.append("agent_phone", this.state.agentPhone);
    formData.append("agent_id", this.state.agentID);
    formData.append("agent_password", this.state.agentPassword);
    formData.append("state", this.state.selectedState);
    formData.append("city", this.state.selectedCity);
    formData.append("file", this.state.file);
    formData.append("imageurl", this.state.imageUrl);
   fetch("http://localhost:4000/add_delivery_agent", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((responsejson) => {
        console.log(responsejson);
      });

and then on server side i did

exports.addDeliveryAgent = async (req, res, next) => {
  let data = req.body;
  console.log(data);
  }
};

but console.log(data) gives me empty object always, what am i doing wrong here ?

Also the data gets posted via axios but i want it via fetch !

App.js config is

const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const mongoconnect = require("./utils/database").mongoconnect;
const path = require("path");
var cors = require("cors");

// const adminUserRoute = require("./routes/admin/user/user.js");
const adminDeliveryAgentRoute = require("./routes/admin/deliveryAgent/deliveryAgent");
const user = require("./routes/admin/user/user.js");

app.use(express.urlencoded());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cors());
app.use("/tfd/controlcenter/", express.static(path.join(__dirname, "/build")));

// app.use(adminUserRoute);
app.use(adminDeliveryAgentRoute);
app.use(user);

mongoconnect(() => {
  app.listen(4000, () => {
    console.log("running 4000");
  });
});
Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48

2 Answers2

0

try adding Content-Type header

   fetch("http://localhost:4000/add_delivery_agent", {
      method: "POST",
      body: formData,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // or
        // 'Content-Type': multipart/form-data
      },
    })
Daniel
  • 2,288
  • 1
  • 14
  • 22
0

Don't use form data instead use plain object as bodyparser doesn't support multipart/form-data which is what form data uses

formData={}

formData.agent_name=this.state.agentName;
formData.agent_email=this.state.agentEmail;
//..
formData.imageurl=this.state.imageUrl;

fetch("http://localhost:4000/add_delivery_agent", {
  method: "POST",
  body: formData,
})
  .then((response) => response.json())
  .then((responsejson) => {
    console.log(responsejson);
  });
Vinay
  • 7,442
  • 6
  • 25
  • 48