nodejs发起http或https请求

2023-12-13 03:50:36

前言:使用node内置模块http、https

http请求

const express = require('express')
const http = require('http')

const app = express()

const loginConfig = (token) => {
  return {
    hostname: 'api.test.com',
    port: 80,
    path: `/test?access_token=${token}`,
    method: 'GET'
  }
}

app.get('/login', (req, res) => {
  const options = loginConfig(req.query.token)
  const http_req = http.request(options, (result) => {
    let data = ''
    result.on('data', (chunk) => {
      data += chunk
    })
    result.on('end', () => {
      data = JSON.parse(data)
      res.send({ code: 200, msg: 'success', data })
    })
  })
  http_req.end()
})

https请求

const express = require('express')
const https = require('https')

const app = express()

const loginConfig = (token) => {
  return {
    hostname: 'api.weixin.qq.com',
    port: 443,
    path: `/wxa/checksession?access_token=${token}`,
    method: 'GET'
  }
}

app.get('/wx_login', (req, res) => {
  const options = loginConfig(req.query.token)
  const https_req = https.request(options, (result) => {
    let data = ''
    result.on('data', (chunk) => {
      data += chunk
    })
    result.on('end', () => {
      data = JSON.parse(data)
      res.send({ code: 200, msg: 'success', data })
    })
  })
  https_req.end()
})

文章来源:https://blog.csdn.net/qq_41579327/article/details/134869247
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。