反应“fetch()"可以“得到"但从不“发帖" [英] React "fetch()" Can "Get" but Never "Posts"

查看:22
本文介绍了反应“fetch()"可以“得到"但从不“发帖"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 中获取"命令的新手.我可以用它来 GET,但我没有用它来 POST.我运行以下简单代码.

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));
}

POST 请求的内容通过以下代码在后端进行处理.

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);
});

因此,网络浏览器应该为响应创建一个警告框,这正是我在请求中发送的内容.那没有发生.我查看了我的服务器日志,发现没有发出 POST 请求.fetch"函数似乎忽略了method"参数.它总是执行GET"请求,即使我告诉它执行POST"请求.我知道在另一篇文章中,他们说请求中的 URL 末尾需要有一个斜杠(fetch() 在 react-native (iOS) 上执行 GET 而不是 POST).但是,这里的情况并非如此.有没有其他人看到有什么问题?

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?

2018 年 3 月 3 日

EDIT 3-3-2018:

按照建议,我包含了标题.但是,该软件仍然发送 GET 而不是 POST 请求.现在使用fetch"的代码如下.还有什么问题?

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);
}

推荐答案

您还必须包含 headers 以表明您的内容是 application/json 类型.

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)

这篇关于反应“fetch()"可以“得到"但从不“发帖"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆