electron发送post请求

参考官网地址:(https://www.electronjs.org/zh/docs/latest/api/net)
src/http.ts

ts 复制代码
import { net } from 'electron';
// ----------网络请求封装--
/**
 * POST请求数据接口
 * @param api 接口地址,如:'http://192.168.1.110/user/login'
 * @param data 请求数据,JOSN 格式,或 object 或 string
 */
export function sendPOST(api:string,data:JSON|object|string){
sendPOST_ASYNC(api,data)
  .then(response => {
    console.log('POST 请求成功: ',response);
    return response;
  }).catch(err => {
    console.log('POST 请求异常: ',err);
    return null;
  })
}
/**
 * GET请求数据接口
 * @param api 接口地址,如:'http://192.168.1.110/ping'
 */
export function sendGET(api:string){
  sendGET_ASYNC(api)
  .then(response => {
    console.log('GET 请求成功: ',response);
    return response;
  }).catch(err => {
    console.log('GET 请求异常: ',err);
    return null;
  })
}
/**
 * POST请求数据接口 - 异步接口
 * @param api 接口地址,如:'http://192.168.1.110/user/login'
 * @param data 请求数据,JOSN 格式,或 object 或 string
 */
async function sendPOST_ASYNC(api:string,data:JSON|object|string){
  const request:RequestInit = {
   method:'POST',
   body:JSON.stringify(data),
   headers:{'Content-Type':'application/json'}
  }
  const response = await net.fetch(api,request)
  if (response.ok) {
    const body = await response.json()
    return body
  }
}
/**
 * GET请求数据接口 - 异步接口
 * @param api 接口地址,如:'http://192.168.1.110/ping'
 */
async function sendGET_ASYNC(api:string){
  const response = await net.fetch(api)
  if (response.ok) {
    const body = await response.json()
    return body
  }
}

main.ts 使用

ts 复制代码
import { sendPOST,sendGET } from './http';
sendPOST('http://192.168.1.110/user/login',{username:"xxx",pwd:"xxx"});
sendGET('http://192.168.1.110/ping')
相关推荐
蓝莓味的口香糖5 分钟前
【vue】初始化 Vue 项目
前端·javascript·vue.js
aikongmeng11 分钟前
【Ai】Claude Code 初始化引导
javascript
光影少年40 分钟前
数组去重方法
开发语言·前端·javascript
我命由我1234540 分钟前
浏览器的 JS 模块化支持观察记录
开发语言·前端·javascript·css·html·ecmascript·html5
weixin_443478511 小时前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
武藤一雄1 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
啥都不懂的小小白1 小时前
前端CSS入门详解
前端·css
林恒smileZAZ2 小时前
前端大屏适配方案:rem、vw/vh、scale 到底选哪个?
开发语言·前端·css·css3
QQ5110082852 小时前
基于区块链的个人医疗咨询挂号信息系统vue
前端·vue.js·区块链
程序员小寒4 小时前
JavaScript设计模式(八):命令模式实现与应用
前端·javascript·设计模式·ecmascript·命令模式