添加依赖
npm install request cheerio async -save
复制
request
var request = require('request');
// 通过 GET 请求来读取 http://cnodejs.org/ 的内容
request('http://cnodejs.org/', function (error, response, body) {
if (!error && response.statusCode == 200) {
// 输出网页内容
console.log(body);
}
});
复制
请求跨域的解决方式
// Create the browser window.
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
webSecurity: false,
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
}
});
app.commandLine.appendSwitch("disable-features", "OutOfBlinkCors");
复制
主要添加了第6行和第11行,正式运行时删除即可
文件夹路径
const { app } = require('electron')
app.getPath(name)
复制
app位于主进j程中,渲染进程
const { app } = window.require("electron").remote;
复制
String - You can request the following paths by the
name
:
-
用户的 home 文件夹(主目录)home
- appData
Per-user application data directory, which by default points to:
- `%APPDATA%` Windows 中
复制
-
or$XDG_CONFIG_HOME
Linux 中~/.config
-
macOS 中~/Library/Application Support
-
储存你应用程序设置文件的文件夹,默认是userData
文件夹附加应用的名称appData
-
临时文件夹temp
-
当前的可执行文件exe
-
Themodule
库libchromiumcontent
-
当前用户的桌面文件夹desktop
-
用户文档目录的路径documents
-
用户下载目录的路径downloads
-
用户音乐目录的路径music
-
用户图片目录的路径pictures
-
用户视频目录的路径videos
-
Directory for the user’s recent files (Windows only).recent
-
应用程序的日志文件夹logs
-
Pepper Flash 插件的系统版本的完成路径。pepperFlashSystemPlugin
-
Directory where crash dumps are stored.crashDumps
-
Returns
String
- A path to a special directory or file associated with
name
. On failure, an
Error
is thrown.
If
app.getPath('logs')
is called without called
app.setAppLogsPath()
being called first, a default log directory will be created equivalent to calling
app.setAppLogsPath()
without a
path
parameter.
文件下载
添加
npm install node-fetch --save
复制
引用
var fetch = window.require("node-fetch");
var fs = window.require("fs");
复制
下载
download(u, p) {
var path = this.outpath + "\\" + p;
return fetch(u, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" }
})
.then(res => res.buffer())
.then(_ => {
fs.writeFile(path, _, "binary", function(err) {
console.log(err || path);
});
});
}
down_action() {
var url =
"http://shiti_upload.91taoke.com/upload/2019/11/23/1548420902.files/image001.png";
this.download(url, url.split("/").reverse()[0]);
}
复制
文件上传
electron写应用时,会遇到自动上传的需求。但是H5中只能通过input(type=file)来手动上传,JS又没有读取文件的权限,此时,我们可以借助node模块完成需求。
const request = require("request");
var options = {
'method': 'POST',
'url': 'https://www.psvmc.com/api2/upload',
'headers': {
'Host': 'www.psvmc.com',
'Referer': 'https://www.psvmc.com/restore',
'Cookie': ''
},
formData:{
file:fs.createReadStream(`./widget.jpg`),
type:'image/jpg',
name:'widget.jpg'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(JSON.parse(response.body));
});
复制