Formdata请求ShortPixel API

时间:2018-11-26 00:06:07

标签: node.js axios multipartform-data

我正在尝试对ShortPixel发出请求,以防它是包含multipart / form-data的请求,并且我收到退货

{ Status: { Code: -115, Message: 'Uploaded files are missing.' } } }

API链接https://shortpixel.com/api-docs#reducer-api-params

const FormData = require("form-data")
const axios = require('axios')
const data = new FormData();
const url = 'https://api.shortpixel.com/v2/post-reducer.php'

const config = {  headers: {
  'accept': 'application/json',
  'Accept-Language': 'en-US,en;q=0.8',
  'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
}}

data.append('hiroshi.png', fs.createReadStream("/home/hiroshi/Documents/projetos/compress/imagens/original/hiroshi.png"), 'hiroshi.png');


axios.post(url,options,{formData:data}, config)
  .then((response) => {
    console.log(response)
  }).catch((error) => {
   console.log(error)
  });

1 个答案:

答案 0 :(得分:0)

我不确定请求多部分表单数据是什么意思。我只是将表单数据收集到服务器端的对象中,然后像这样发送:

let postData =  { 
    "key": "api_key_here",
    "plugin_version": "JS123",
    "lossy": 1,
    "cmyk2rgb": 1,
    "refresh": 1,
    "resize": 3,
    "wait":30,
    "resize_width":100,
    "resize_height":100,
    "urllist":["http://example.com/example.png", "http://example.com/example2.png"]
    }

    axios.post('https://api.shortpixel.com/v2/reducer.php',postData, {
        headers: {
        "Content-Type": "application/json"
        }
    })
    .then(function (response) {
        console.log(response.data);
    })
    .catch(function (error) {
        console.log(error);
    });

您可以在我上面创建的postData对象中添加任何变量。

edit:哦,我明白了,您正在使用post-reducer api,而上面我只是使用reducer。解决了吗?