我正在浏览电子js,但我面临的问题是编写restful。在没有react.js、express和falcon vue.js的情况下,几乎没有任何资源能够显示API的使用情况。我编写python只是为了测试而添加两个数字,但我不知道如何在电子中使用restful,而不使用任何其他语言,比如react/express/falcon,因为它会增加我的学习曲线。帮助感激。
注意:我的API是托管的。
发布于 2020-03-27 15:38:15
有两种内置方法,您可以使用它们而不是使用axios、jQuery Ajax、.
提取:
使用Fetch API非常简单。只需将URL、要获取的资源的路径传递给fetch()方法即可。
简单的获取方法:
//simple GET method
fetch('/js/users.json')
.then(response => {
// handle response data
})
.catch(err => {
// handle errors
});
其他方法如POST
、DELETE
、.:
// 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请求。
让xhr =新XMLHttpRequest();
Xhr.open(方法、URL、异步、用户、密码)
- `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).
Xhr.send(身体)
此方法打开连接并将请求发送到服务器。可选的body参数包含请求主体。
一些请求方法(如GET )没有身体。他们中的一些人,如POST,使用body将数据发送到服务器。我们将看到用于响应的later.
这三个事件是使用最广泛的:
- `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 =真的字节数是多少;};
https://stackoverflow.com/questions/60887076
复制相似问题