尝试使用 Axios / node-fetch 将 apk 文件上传到 Browserstack 云时出错

Error while trying to upload apk file to Browserstack cloud, using Axios / node-fetch

我正在尝试以编程方式将 .apk / .ipa 文件上传到 browserstack 云(而不是 运行 curl 命令)

选项 1:节点获取 api

const myfetch = require('node-fetch');

const buildToPost = {
   file: '</my path>'
};

const options = {
   method: 'POST',
   body: JSON.stringify(buildToPost)
};

myfetch('https://</myusername>:</mykey>@api.browserstack.com/app-automate/upload', options)
   .then(res => res.json())
   .then(res => console.log(res))
   .catch(error => console.error('Error:', error));​

但出现以下错误:

{ error: 'Invalid format. Refer to REST API document for valid API format - https://www.browserstack.com/app-automate/rest-api' }

选项 2:Axios API

    const axios = require('axios');

axios.post('https://</myusername>:</mykey>​@api-cloud.browserstack.com/app-automate/upload', {
      File: '</my path>​'
   })
   .then
   ((response) => {
      console.log(response);
   }).catch((error) => {
      console.log((error));
})​

错误:数据:

{ error: 'Invalid format. Refer to REST API document for valid API format - https://www.browserstack.com/app-automate/rest-api' } } }

curl 命令参考:

curl -u "</myusername>:</mykey>" -X POST https://api-cloud.browserstack.com/app-automate/upload -F "file=@/path/to/app/file/Application-debug.apk" -F 'data={"custom_id": "MyApp"}'

Browserstack sample link

以下是 axios 的操作方法。重点是:

  • 身份验证(使用 user 选项)
  • 使用FormData模块提交多部分数据
  • maxContentLength 选项设置得足够高以允许上传您的文件。

下面的代码。

import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';

const formData = new FormData();

// Open file stream
const newFile = fs.createReadStream(binaryPath);

// Add form field params
formData.append('file', newFile, 'my_filename.apk');
formData.append('custom_id', 'npm_uploaded_apk');

axios({
  url: 'https://api-cloud.browserstack.com/app-automate/upload',
  method: 'post',
  headers: formData.getHeaders(),
  auth: {
    username:'my_browserstack_username',
    password: 'my_browserstack_access_key',
  },
  data: formData,
  maxContentLength: 1073741824,
})
  .then(response => {
    // The object with the 'app_url' parameter is in the 'data' field of the response.
    console.log('POST successful: ', response.data);
  })
  .catch((error) => {
    console.log('POST error: ', error);
  });

this GitHub thread 中的更多背景信息。