electron的网络请求:
使用Chromium的原生网络库发出HTTP / HTTPS请求
net 模块是一个发送 HTTP(S) 请求的客户端API。 它类似于Node.js的HTTP 和 HTTPS 模块 ,但它使用的是Chromium原生网络库来替代Node.js的实现,提供更好的网络代理支持。
实例GET请求:https://electronjs.org/docs/api/net
const { app } = require('electron')
app.on('ready', () => {
const { net } = require('electron') //引入net
const request = net.request('https://www.baidu.com') //输入地址
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
ClientRequest实现了Writable Stream接口, 因此是一个EventEmitter类型.
new ClientRequest(options)
参数 (Object | String) -如果 选项 是一个String类型, 它被解释为请求的URL. 如果它是一个Object类型, 那么它可以通过以下属性指定一个HTTP请求:
- method String (可选) - HTTP请求方法. 默认为GET方法.
- url String (可选) - 请求的URL. 必须在指定了http或https的协议方案的独立表单中提供.
- session Object (可选) - 与请求相关联的Session实例.
- partition String (可选) - 与请求相关联的partition名称. 默认为空字符串.
- session选项优先于partition选项. 因此, 如果session是显式指定的, 则partition将被忽略.
- protocol String (可选) - 在"scheme:"表单中的协议方案. 目前支持的值为’http:’ 或者’https:’.
默认为’http:’. - host String (可选) - 作为连接提供的服务器主机,主机名和端口号’hostname:port’.
- hostname String (可选) - 服务器主机名
- port Integer (可选) - 服务器侦听的端口号.
- path String (可选) - 请求URL的路径部分.
- redirect String (可选) - 请求的重定向模式. 可选值为 follow, error 或 manual. 默认值为 follow. 当模式为error时, 重定向将被终止. 当模式为 manual时,表示延迟重定向直到调用了 request.followRedirect。 在此模式中侦听 redirect事件,以获得关于重定向请求的更多细节。
- options 属性,如 protocol, host, hostname, port 和 path,在 URL 模块中会严格遵循 Node.js 的模式
POST:https://electronjs.org/docs/api/client-request
const request = net.request({
method: 'POST',
protocol: 'http:',
hostname: 'github.com',
port: 443,
path: '/'
})
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
可以在控制台看到打印的内容