0

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();
});
12
  • New records do have the name set or its empty ? Commented Dec 20, 2018 at 10:04
  • New records do not have name set, they are empty. Commented Dec 20, 2018 at 10:06
  • Did you use app.use(bodyParser.json()); and then check? Commented Dec 20, 2018 at 10:10
  • You should then first debug your backend code, add some debug info with console.log (dumping the captured body data) or put a breakpoint and inspect the request. Something like : console.log(JSON.stringify(req.body)) before the new Competitor.. Commented Dec 20, 2018 at 10:10
  • I think the error is with bodyparser. Have you added the middleware in the express or configured it correctly. try logging the request data with console.log(req.body) on the route Commented Dec 20, 2018 at 10:19

2 Answers 2

2

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I did everything. But still the same. console.log(req.body) shows: [object Object]
Sorry, it works! I just had to change back 'Content-Type' to 'application/json' because I changed it because of another answer. Thank you very much!
@TomaszPaczka you have to sync both request headers with what your controller is expecting. Either 'json' or 'x-www-form-urlencoded' as 'Content-Type' will work fine if the headers and format of body are correct
1

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}`

5 Comments

Still the same. And with this header when I console.log(req.body) in server route, it showed errors: POST localhost:5000/competitors 500 (Internal Server Error) and Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I don't understand, what is also=another?
that was just to indicate that you can pass more than one parameter in the same string. I edited the answer to match your request
It depends on which Content Type you are willing to use :)
Yes, I was trying to check all options which you guys telling me and I mixed it a little bit up so it didn't work. I know that your option could work too, it just that works better for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.