我可以在React应用程序中使用什么作为Angular的等价物;s$http.get

What can I use in a React app as an equivalent of Angular's $http.get

本文关键字:等价物 Angular get http 应用程序 React 什么 我可以      更新时间:2023-09-26

我想在React应用程序中发出http请求,我想知道最好的方法是什么。我知道在Angular中你可以使用$http.get,所以类似于:

$http.get('API').success(function(data) {...

但是,在React应用程序中,我可以使用什么来达到同样的目的。像Axios这样的东西能用吗?

原谅我的无知,这里的新手。

检出window.fetch。它有一个非常好用的API。它是一个fetch函数,现在在全局窗口范围内提供。

如果您想在不实现fetch的情况下支持浏览器。试试github的这种polyfillhttps://github.com/github/fetch

这里有一个的快速示例

// url (required), options (optional)
fetch('/some/url', {
    method: 'get'
}).then(function(response) {
    if (response.ok) {
        return response.json()
    }
}).then(function(json) {
    console.log(json)
    // set your state, your props, your child context do whatever you want
    // with the json
    // this.setState({ data: json })
}).catch(function(err) {
    // Error :(
})

这里有一个伟大的教程

这是的规格

您可以使用JQuery库的ajax方法或Superagent等特定库。对于Superagent,只需将其与npm一起安装,例如npm i superagent --save,并发出http请求,例如:

request
   .get('/search')
   .end(function(err, res){
       // function body
   });

以下是完整的文档。