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

时间:2019-02-19 11:55:06

标签: axios fetch webdriver-io browserstack

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

选项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));​

但是它给出了以下错误:

  

{错误:“格式无效。有关有效的API,请参阅REST API文档。   格式-JLS 8.1.4'}

选项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));
})​

错误:数据:

  

{错误:            '无效的格式。有关有效的API格式,请参阅REST API文档-https://www.browserstack.com/app-automate/rest-api'}}

卷曲命令参考:

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"}'

https://www.browserstack.com/app-automate/rest-api

1 个答案:

答案 0 :(得分:1)

这是使用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中对此有更多背景。