Javascript Electron Restful Api,不含react或任何其他express
我正在学习electron js,但我面临的问题是编写restful API。如果没有react.js、express和falcon vue.js,几乎没有任何资源显示API的使用情况。我编写pythonapi只是为了测试而添加两个数字,但我不知道如何在没有任何其他语言(如react/express/falcon)的情况下在electron中使用这些restfulapi,因为这会增加我的学习曲线。 谢谢你的帮助Javascript Electron Restful Api,不含react或任何其他express,javascript,node.js,ajax,electron,desktop-application,Javascript,Node.js,Ajax,Electron,Desktop Application,我正在学习electron js,但我面临的问题是编写restful API。如果没有react.js、express和falcon vue.js,几乎没有任何资源显示API的使用情况。我编写pythonapi只是为了测试而添加两个数字,但我不知道如何在没有任何其他语言(如react/express/falcon)的情况下在electron中使用这些restfulapi,因为这会增加我的学习曲线。 谢谢你的帮助 注意:我的API是托管的有两种内置方法,您可以使用它们来代替axios、jQuery
注意:我的API是托管的有两种内置方法,您可以使用它们来代替axios、jQuery Ajax等框架 获取: 使用fetchapi非常简单。只需将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请求
let xhr = new XMLHttpRequest();
xhr.open(method, URL, [async, user, password])
let xhr = new XMLHttpRequest();
xhr.open(method, URL, [async, user, password])
–HTTP方法。通常方法
或“获取”
“发布”
–请求的URL,一个字符串,可以是URL对象URL
–如果显式设置为async
,则请求是同步的,稍后我们将介绍这一点false
,用户
–基本HTTP身份验证的登录名和密码(如果需要)密码
xhr.send([body])
此方法打开连接并将请求发送到服务器。可选的
body参数包含请求主体
有些请求方法(如GET)没有主体。他们中的一些人喜欢邮局
使用body将数据发送到服务器。稍后我们将看到这方面的示例
–当请求完成时(即使HTTP状态为400或500),响应被完全下载加载
xhr.onload = function() {
alert(`Loaded: ${xhr.status} ${xhr.response}`);
};
xhr.onerror = function() { // only triggers if the request couldn't be
made at all
alert(`Network Error`);
};
xhr.onprogress = function(event) { // triggers periodically
// event.loaded - how many bytes downloaded
// event.lengthComputable = true if the server sent Content-Length
// header
// event.total - total number of bytes (if lengthComputable)
alert(`Received ${event.loaded} of ${event.total}`);
};
错误
–当无法发出请求时,例如网络关闭或URL无效进度
–在下载响应时定期触发,报告下载量
xhr.onload = function() {
alert(`Loaded: ${xhr.status} ${xhr.response}`);
};
xhr.onerror = function() { // only triggers if the request couldn't be
made at all
alert(`Network Error`);
};
xhr.onprogress = function(event) { // triggers periodically
// event.loaded - how many bytes downloaded
// event.lengthComputable = true if the server sent Content-Length
// header
// event.total - total number of bytes (if lengthComputable)
alert(`Received ${event.loaded} of ${event.total}`);
};