node 通过axios发送post请求(FormData)

方案一:

const axios = require('axios')
const FormData = require('form-data')
const fs = require('fs')



const sdUpscaleOnAzure = async (req, res) => {
    const data = new FormData()
    data.append('image', fs.readFileSync('/temp/ai/sd/download/1.png'))
    let config = {
      headers: {
        ...data.getHeaders(),
        Accept: 'application/json',
      },
      method: 'post',
    }

    config.url = 'https://www.baidu.com'
    config.data = data
    console.log(config)

    axios({
      ...config,
    })
      .then(async (response) => {
          res.send({
            code: 200,
            data: {
              response: response.data,
            },
            message: '成功',
          })

      })
      .catch((err) => {
        res.send({
          code: 400,
          data: {
            err,
          },
          message: '失败2',
        })
      })
}

方案二:

      const data = new FormData()
      let tempData = config.data
      for (let key in tempData) {
        data.append(key, tempData[key])
      }
      config.data = data
      config.headers['Content-Type'] =
        'multipart/form-data; boundary=' + data.getBoundary()
    
    axios({
      ...config,
    })
      .then((response) => {
        res.send({
          code: 200,
          data: {
            response: response.data,
          },
          message: '成功',
        })
      })
      .catch((err) => {
        res.send({
          code: 400,
          data: {
            err,
          },
          message: '失败',
        })
      })

参考链接:

https://chat.xutongbao.top/

posted @ 2023-10-16 16:32  徐同保  阅读(25)  评论(0编辑  收藏  举报  来源