繁体   English   中英

使用获取API发布反应

[英]Using fetch api to post in react

我有一个消息方法,当我单击表单上的“提交”按钮时会触发该消息。 但是我无法访问节点rest api中的URL,我试图通过“ req.body.url”访问URL,该URL返回未定义,当我看到req.body中不存在任何内容时。 我已经使用axios做到了这一点,效果很好,可以帮助我使用提取

    message(event){
       event.preventDefault();
           const uri = this.state.short.url;
             fetch("http://localhost:3000/messages", {
              method: "post",
              body: {url: uri}
              })
            .then(function(data) {
          console.log("Request succeeded with  response", data);
           })
       .catch(function(error) {
           console.log("Request failed", error);
         });
    }

在您的提取操作中,您需要指定Json并像这样将json字符串化:

body: JSON.stringify({ url: uri }),
 headers:{
   'Content-Type': 'application/json'
}

没有您的更多信息,我想这就是您想要的:

fetch("http://localhost:3000/messages", {
    method: "post",
    body: JSON.stringify({url: uri})
    })
.then(function(response) {
    if(response.ok){
        return response.json();
    }{
        throw new Error("Post Failed")
    }
}).then(function(responseBody){
    console.log(responseBody.uri)
})
.catch(function(error) {
    console.log("Request failed", error);
});

这是一个非常相似的可运行版本。 它使用的服务只是回显数据以进行测试。

  fetch("http://httpbin.org/post", { method: "POST", body: JSON.stringify({url: "test"}) }) .then(function(response) { if(response.ok){ return response.json(); }{ throw new Error("Post Failed") } }).then(function(responseBody){ console.log(responseBody) }) .catch(function(error) { console.log("Request failed", error); }); 

const options = {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ url: uri})
};

fetch("http://localhost:3000/messages", options)
  .then(response => response.json())
  .then(data =>console.log(data));
}

暂无
暂无

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

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