如何通过GET请求使用fetch API发送数据?

9
我想通过fetch API将一些数据发送到服务器,以便它可以根据这些数据查询数据库。与Ajax不同,我找不到合适的方法来实现这一点。 以下是我的fetch调用:
{fetch("http://192.168.90.53:4000/game/?email=adicool2294@gmail.com", {method: "GET"} )
        .then((response) => response.json())
        .then((responseData) => {
            id= responseData.id;
            name= responseData.name; 
            console.log(responseData);
        })
       .catch((error) => {
             console.warn(error);
           }); 
  }
}

我想发送一个参数,比如电子邮件,这样服务器就可以使用它来查询数据库。由于我正在使用React Native Android,所以无法使用Ajax请求。 我只想使用GET方法。目前,在URL中传递的查询参数在服务器的req.query中没有显示出来。
3个回答

9

GET请求不支持传递消息体,必须像您在示例中展示的那样将参数发送到URL中。如果您无法在服务器端看到它们,则可能是服务器问题,应作为单独的问题进行询问。

作为一项合理性测试,在浏览器中(或像Postman这样的工具中)导航到该URL并测试结果是否正确,然后再使用fetch实现调用,这样您至少可以确认它是服务器问题还是JavaScript问题。


2
GET请求确实支持请求体。请查看:https://tools.ietf.org/html/rfc7231#page-24,同时也可以参考ElasticSearch关于此的页面:https://www.elastic.co/guide/en/elasticsearch/guide/current/_empty_search.html - Ebram Shehata

2
尝试使用 %40 对 @ 符号进行转义,或者像下面这样做: {fetch("http://192.168.90.53:4000/game/?email=" + encodeURIComponent('adicool2294@gmail.com'), {method: "GET"} )... 这样做可以保留 HTML 标签。

-3
You can add that like below

fetch("http://192.168.90.53:4000/game", obj)  
.then(function(response) => response.json())
.then((responseData) => {
  id = responseData.id;
  name = responseData.name; 
  console.log(responseData);
},
.catch((error) => {
  console.warn(error);
}); 

var obj = {  
  method: 'POST',
  body: JSON.stringify({
    'email': your_email_here,
  })
};

我不想使用POST方法,我想用GET方法发送查询参数。目前,虽然我正在使用URL发送参数,但服务器没有在req.query中显示它。该怎么办? - Aditya Rohilla
那么,您尝试以John Shammas的身份导航到该URL了吗?如果不起作用,您可以尝试使用其他URL,而不是本地服务器(只是猜测,因为我最近在本地主机上遇到了问题)。 - Liem Ly Quan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接