首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >电子Restful Api无反应或任何其他表示

电子Restful Api无反应或任何其他表示
EN

Stack Overflow用户
提问于 2020-03-27 13:31:57
回答 1查看 759关注 0票数 0

我正在浏览电子js,但我面临的问题是编写restful。在没有react.js、express和falcon vue.js的情况下,几乎没有任何资源能够显示API的使用情况。我编写python只是为了测试而添加两个数字,但我不知道如何在电子中使用restful,而不使用任何其他语言,比如react/express/falcon,因为它会增加我的学习曲线。帮助感激。

注意:我的API是托管的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-27 15:38:15

有两种内置方法,您可以使用它们而不是使用axios、jQuery Ajax、.

提取:

使用Fetch API非常简单。只需将URL、要获取的资源的路径传递给fetch()方法即可。

简单的获取方法:

代码语言:javascript
运行
复制
//simple GET method
fetch('/js/users.json')
    .then(response => {
        // handle response data
    })
    .catch(err => {
        // handle errors
    });

其他方法如POSTDELETE、.:

代码语言:javascript
运行
复制
// some data to post
const user = {
    first_name: 'John',
    last_name: 'Lilly',
    job_title: 'Software Engineer'
};

// options of fetch
const options = {
    method: 'POST',
    body: JSON.stringify(user),
    headers: {
        'Content-Type': 'application/json'
    }
}

fetch('https://reqres.in/api/users', options)
    .then(response => {
        // handle response data
    })
    .catch(err => {
        // handle errors
    });

XML HttpRequest:

XMLHttpRequest是一个内置的浏览器对象,允许在JavaScript中发出HTTP请求。

  1. 创建XMLHttpRequest:

让xhr =新XMLHttpRequest();

  • Initialize it,通常在新XMLHttpRequest之后:

Xhr.open(方法、URL、异步、用户、密码)

代码语言:javascript
运行
复制
- `method` – HTTP-method. Usually `"GET"` or `"POST"`.
- `URL` – the URL to request, a string, can be URL object.
- `async` – if explicitly set to `false`, then the request is synchronous, we’ll cover that a bit later.
- `user`, `password` – login and password for basic HTTP auth (if required).

  1. 把它发出去了。

Xhr.send(身体)

此方法打开连接并将请求发送到服务器。可选的body参数包含请求主体。

一些请求方法(如GET )没有身体。他们中的一些人,如POST,使用body将数据发送到服务器。我们将看到用于响应的later.

  • Listen到xhr事件的示例。

这三个事件是使用最广泛的:

代码语言:javascript
运行
复制
- `load` – when the request is complete (even if HTTP status is like 400 or 500), and the response is fully downloaded.
- `error` – when the request couldn’t be made, e.g. network down or invalid URL.
- `progress` – triggers periodically while the response is being downloaded, reports how much has been downloaded.

xhr.onload = function() {Loaded: ${xhr.status} ${xhr.response};};xhr.onerror = function() { //仅在无法发出请求的情况下触发(Network Error);};xhr.onprogress =function(事件){ //触发器/定期/ event.loaded -如果服务器发送内容-长度//头/头/ event.total -字节总数(如果lengthComputable)警报(Received ${event.loaded} of ${event.total}),那么下载// event.lengthComputable =真的字节数是多少;};

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60887076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档