简体   繁体   中英

Post request from ReactJs

I want to receive the post request from front end using ReactJs. The api is working and i get a get request, also my React Component is working. This is my post request from the React component:


  
 
  
  
  
function submitBtn() {
    
return (
 fetch("api", {
  method: "POST",
  headers : { 
  'Content-Type':'application/json',
  'Accept':'application/json'
  },
  body: JSON.stringify('my data')
  }).then(res => {
  console.log("Request complete! response:", res);
   })
    )
     }
  return (
       <div>
            <input ref={nameRef} type='text' placeholder='name' name='firstName' />
            <input ref={lastnameRef} type='text' placeholder='last name' name='lastName' />
         <button onClick={submitBtn} type='submit'>Fetch</button>
      </div>
    )
    ...

Bellow is my NodeJs code:


  
 
  
  
  
    app.post('/api', function (req, res) {
       console.log("Got a POST request");
       res.json({ username: req.body.firstName, lastname: req.body.lastName  });
       res.sendStatus(200);
    })

Also, i used bodyParser. The problem is that i can't receive data from my post request? What could be the issue? Also i get the issue: Unexpected token " in JSON at position 0 . What this could be in my case?

Your JSON is not correct. While sending fetch request body must be stringified JSON.

 function submitBtn() { return ( fetch("api", { method: "POST", headers : { 'Content-Type':'application/json', 'Accept':'application/json' }, body: JSON.stringify({firstName: "toto", lastName: "momo"}) }).then(res => { console.log("Request complete! response:", res); }) ) } return ( <div> <input ref={nameRef} type='text' placeholder='name' name='firstName' /> <input ref={lastnameRef} type='text' placeholder='last name' name='lastName' /> <button onClick={submitBtn} type='submit'>Fetch</button> </div> ) ...

Here's an example: https://googlechrome.github.io/samples/fetch-api/fetch-post.html

keep the following things in mind:

  1. body data should be stringified for "Content-Type": "application/json" when using fetch :

    body: JSON.stringify(object)

  2. res.json({ username: req.body.firstName, lastname: req.body.lastName }); will automatically set status as 200 and will end req-res cycle. So calling res.sendSatatus() will throw error because req-res cycle has already ended.

  3. if you want to set status manually with data use

    res.status('statusCode').json(object)

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