React “fetch()” Can “Get” but Never “Posts”

回眸只為那壹抹淺笑 提交于 2019-12-20 03:44:11

问题


I am new to the "fetch" command in React. I can use it to GET, but I have had no luck with using it to POST. I run the following simple code.

onSubmit(event) {
  // For some reason, "fetch" is GETTING instead of POSTING.
  fetch('/questionare/', {
    method: 'post',
    body: JSON.stringify({greeting: "Hello"})
  }).then((res) => alert(res.json));
}

The content of the POST request gets processed on on the back-end by the following code.

router.post('/', function(req, res, next) {
  res.json(req.body);
});

Therefore, the web browser should create an alert box for the response, which is the exact content I sent in the request. That has failed to happen. I have looked at my server log and have been finding that no POST request gets issued. The "fetch" function seems to ignore the "method" parameter. It always does "GET" requests, even if I tell it to do a "POST" request. I know in another post, they said there needs to be a slash at the end of the URL in the request (fetch() doing GET instead of POST on react-native (iOS)). However, that has not been the case here. Does anybody else see what is wrong?

EDIT 3-3-2018:

As suggested, I included the headers. However, the software still sends GET instead of POST requests. The code using "fetch" is now as follows. What else could be wrong?

onSubmit(event) {
  // For some reason, "fetch" is GETTING instead of POSTING.
  fetch('/questionare/', {
    method: 'post',
    body: JSON.stringify({greeting: "Hello"}),
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    })
  })
  .then(res => res.json)
  .then(console.log);
}

回答1:


You have to include the headers as well to indicate that your content is of application/json type.

fetch('/questionaire', {
  method: 'post',
  body: JSON.stringify(data),
  headers: new Headers({
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  })
})
  .then(response => response.json())
  .then(console.log)


来源:https://stackoverflow.com/questions/49080130/react-fetch-can-get-but-never-posts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!