反应“提取()”可以“获取”但从不“帖子” [英] React "fetch()" Can "Get" but Never "Posts"

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

问题描述

我对React中的获取命令很陌生。我可以使用它来获取,但我没有运用它来发布。

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请求。 获取功能似乎忽略了方法参数。即使我告诉它执行POST请求,它总是会发出GET请求。我知道在另一篇文章中,他们说需要在请求的URL末尾有一个斜线(获取()做GET而不是POST在反应本机(iOS))。但是,这并非如此。是否有人看到有什么不对?

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?

编辑3-3-2018:

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


推荐答案

code> 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)

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

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