node端发送请求

206 阅读1分钟

使用request在node端发送请求

npm install request

const request = require('request') // request 默认header就是 form 形式的请求

// 发送 get 请求
const result = await new Promise((resolve, reject) => {
    request({
        url: '',
        method: 'GET',
    }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
            resolve(body)
        } else {
            resolve({})
        }
    })
})

// 发送 application/x-www-form-urlencoded 请求
const form = {
    id: 001,
    name: 'test'
}
const result = await new Promise((resolve, reject) => {
    request({
        url: '',
        method: 'POST',
        form
    }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
            resolve(body)
        } else {
            resolve({})
        }
    })
})

// 发送 application/json 请求
const data = {
    id: 001,
    name: 'test'
}
const result = await new Promise((resolve, reject) => {
    request({
        url: '',
        method: 'POST',
        json: true,
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(data)
    }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
            resolve(body)
        } else {
            resolve({})
        }
    })
})

// 发送 multipart/form-data 请求
const formData = {
    fileName: test,
    fileBuffer: new Buffer([1, 2, 3, 4, 5]),
    file: require('../iamges/test.png')
}
const result = await new Promise((resolve, reject) => {
    request({
        url: '',
        method: 'POST',
        formData
    }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
            resolve(body)
        } else {
            resolve({})
        }
    })
})