Skip to content

http — HTTP 客户端 ​

http 模块提供了 HTTP 请求功能,支持 GET、POST、PUT、DELETE 等方法。

引入方式 ​

javascript
var http = require("http")

API 列表 ​

Get — GET 请求 ​

javascript
var data = http.Get("https://api.example.com/users")

带请求头:

javascript
var data = http.Get("https://api.example.com/users", {
    "Authorization": "Bearer token123"
})

Post — POST 请求 ​

javascript
var data = http.Post("https://api.example.com/users", {
    name: "张三",
    age: 25
})

带请求头:

javascript
var data = http.Post("https://api.example.com/users", {
    name: "张三"
}, {
    "Authorization": "Bearer token123"
})

Put — PUT 请求 ​

javascript
var data = http.Put("https://api.example.com/users/1", {
    name: "李四"
})

Delete — DELETE 请求 ​

javascript
var data = http.Delete("https://api.example.com/users/1")

Request — 自定义方法请求 ​

javascript
var data = http.Request("https://api.example.com/users", "PATCH", {
    name: "张三"
}, {
    "Authorization": "Bearer token123"
})

配置方法 ​

SetTimeout — 设置超时时间 ​

javascript
http.SetTimeout(5000) // 5 秒超时

SetRetry — 设置重试 ​

javascript
http.SetRetry(3, 1000) // 重试 3 次,每次间隔 1 秒

SetProxy — 设置代理 ​

javascript
http.SetProxy("http://proxy.example.com:8080")

SetBaseURL — 设置基础 URL ​

javascript
http.SetBaseURL("https://api.example.com")

SetDefaultHeader — 设置默认请求头 ​

javascript
http.SetDefaultHeader("Authorization", "Bearer token123")

完整示例 ​

javascript
var http = require("http")

// 获取用户列表
var users = http.Get("https://api.example.com/users")

// 创建用户
var result = http.Post("https://api.example.com/users", {
    name: "张三",
    age: 25,
    email: "zhangsan@example.com"
})

// 带认证的请求
var data = http.Get("https://api.example.com/profile", {
    "Authorization": "Bearer " + token
})

// 调用第三方 API
var weather = http.Get("https://api.weather.com/current?city=北京", {
    "API-Key": "your-api-key"
})

注意事项 ​

  • HTTP 请求为同步调用,会阻塞脚本执行
  • 建议设置合理的超时时间,避免长时间等待
  • 大量请求建议设置重试机制

版权所有.