简体   繁体   中英

Problem with POST request from React.js component to Node.js server

I'm trying to send data from client's inputs based on React.js to server written in Node.js which put it to DB. I have no errors and after submit, new records show in database but they are empty. I have two inputs and I'm joining them in one string and trying send it to DB (so DB has one property). Can you check my code and see what is wrong? Maybe something with headers...

This is function in React component:

  addCompetitor = event => {
    event.preventDefault();
    const name = this.state.draftCompetitorName;
    const lastname = this.state.draftCompetitorLastname;
    fetch(`http://localhost:5000/competitors`, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name: `${name}${lastname}` })
    })
      .then(response => response.json())
   };

This is server POST response:

  app.post("/competitors/", urlencodedParser, function (req, res) {
    const newCompetitor = new Competitor({ name: req.body.name });
    newCompetitor.save().then(competitor => res.json(competitor));
  });

And it's app configuration:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type",
    "X-Requested-With"
  );
  res.setHeader("Access-Control-Allow-Credentials", true);
  next();
});

If not first install bodyparser . This parses incoming request bodies in a middleware before your handlers, which will be available under the req.body property.

app.use(bodyParser.json({
  limit: '50mb',
  parameterLimit: 100000
}))

Alternatively what is the express version you are using ? Is it greater than 4.16? Then you can also use

app.use(express.json()); 

See notes here

https://expressjs.com/en/api.html#express.json

Modify your code

let databody = {
        "name": `${name}${lastname}`,
        "otherprop": this.state.otherprop
}

From frontend use body: JSON.stringify(databody),

In express end remove urlencodedParser , should be like below:

app.post("/competitors", function (req, res) {
    console.log(req.body);
});

You are using urlencodedParser as a middleware so I guess you used bodyParser.urlencoded({}) but your request is sending a json format. Try adjusting your request by adding the following header:

'Content-Type': 'application/x-www-form-urlencoded'

EDIT:

Also body should be in the following format:

body: `name=${name}${lastname}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM