简体   繁体   English

来自 ReactJs 的发布请求

[英]Post request from ReactJs

I want to receive the post request from front end using ReactJs.我想使用 ReactJs 从前端接收发布请求。 The api is working and i get a get request, also my React Component is working. api 正在工作,我收到了一个 get 请求,我的 React 组件也在工作。 This is my post request from the React component:这是我来自 React 组件的 post 请求:


  
 
  
  
  
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:波纹管是我的 NodeJs 代码:


  
 
  
  
  
    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.另外,我使用了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?我也遇到了这个问题: Unexpected token " in JSON at position 0 。在我的情况下这可能是什么?

Your JSON is not correct.您的 JSON 不正确。 While sending fetch request body must be stringified JSON.发送 fetch 请求正文必须是字符串化的 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这是一个例子: 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 :使用fetch时,正文数据应针对"Content-Type": "application/json"进行字符串化:

    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.将自动将状态设置为 200 并结束req-res循环。 So calling res.sendSatatus() will throw error because req-res cycle has already ended.所以调用res.sendSatatus()会抛出错误,因为req-res循环已经结束。

  3. if you want to set status manually with data use如果您想通过数据使用手动设置状态

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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