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

2019-02-26 11: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条回答
Animai°情兽
2楼-- · 2019-02-26 11:38

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)
查看更多
登录 后发表回答