将 cURL 转换为使用 auth、multipart/form-data 和 json 获取

Converting cURL to fetch with auth, multipart/form-data, and json

我正在努力将一些 cURL 转换为 javascript。

我用它来将卷曲转换为 php - https://incarnate.github.io/curl-to-php/ - 这个工具绝对棒极了。但是我在 javascript.

上遇到了困难

我的卷曲是这样的:

curl -X POST -u "{username}:{password}"
--form metadata="{
  \"part_content_type\":\"audio/wav\",
 }"
--form upload="@audio-me.wav"
"https://my.url.here"

我正在尝试这个,但是端点给我失败,没有给出细节,浏览器实际上抛出一个:

TypeError: NetworkError when attempting to fetch resource.

这是我整理的:

let metadata = { part_content_type: 'audio/wav' };

let data = new FormData();
data.append('upload', blob, 'audio-me.wav');
data.append('metadata', JSON.stringify(metadata));
fetch('https://my.url.here', {
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Basic ' + base64_encode(username + ':' + password)
    },
    body: data
}).then(x=>console.log('success:', x)).catch(z=>console.error('fail:',z));

function base64_encode (stringToEncode) { // eslint-disable-line camelcase
//  discuss at: http://locutus.io/php/base64_encode/
// original by: Tyler Akins (http://rumkin.com)
// improved by: Bayron Guevara
// improved by: Thunder.m
// improved by: Kevin van Zonneveld (http://kvz.io)
// improved by: Kevin van Zonneveld (http://kvz.io)
// improved by: Rafał Kukawski (http://blog.kukawski.pl)
// bugfixed by: Pellentesque Malesuada
// improved by: Indigo744
//   example 1: base64_encode('Kevin van Zonneveld')
//   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
//   example 2: base64_encode('a')
//   returns 2: 'YQ=='
//   example 3: base64_encode('✓ à la mode')
//   returns 3: '4pyTIMOgIGxhIG1vZGU='
// encodeUTF8string()
// Internal function to encode properly UTF8 string
// Adapted from Solution #1 at https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
var encodeUTF8string = function (str) {
    // first we use encodeURIComponent to get percent-encoded UTF-8,
    // then we convert the percent encodings into raw bytes which
    // can be fed into the base64 encoding algorithm.
    return encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
    function toSolidBytes (match, p1) {
        return String.fromCharCode('0x' + p1)
    })
}
if (typeof window !== 'undefined') {
    if (typeof window.btoa !== 'undefined') {
    return window.btoa(encodeUTF8string(stringToEncode))
    }
} else {
    return new Buffer(stringToEncode).toString('base64')
}
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
var o1
var o2
var o3
var h1
var h2
var h3
var h4
var bits
var i = 0
var ac = 0
var enc = ''
var tmpArr = []
if (!stringToEncode) {
    return stringToEncode
}
stringToEncode = encodeUTF8string(stringToEncode)
do {
    // pack three octets into four hexets
    o1 = stringToEncode.charCodeAt(i++)
    o2 = stringToEncode.charCodeAt(i++)
    o3 = stringToEncode.charCodeAt(i++)
    bits = o1 << 16 | o2 << 8 | o3
    h1 = bits >> 18 & 0x3f
    h2 = bits >> 12 & 0x3f
    h3 = bits >> 6 & 0x3f
    h4 = bits & 0x3f
    // use hexets to index into b64, and append result to encoded string
    tmpArr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4)
} while (i < stringToEncode.length)
enc = tmpArr.join('')
var r = stringToEncode.length % 3
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3)
}

如果我做错了这个转换,你能告诉我吗?

谢谢

删除 'Content-Type': 'multipart/form-data'.

当您使用 fetch(…) 方法发送 FormData 时,您不需要手动设置 Content-Type 请求 header。见 the relevant part of the Fetch spec:

↪ FormData
Set action to an action that runs the multipart/form-data encoding algorithm, with object as form data set and with UTF-8 as the explicit character encoding.

Set Content-Type to multipart/form-data; boundary=, followed by the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

所以 'Content-Type': 'multipart/form-data' 无论如何都是错误的——因为缺少 boundary=… 部分,它的格式不正确。

但是通过在您的代码中手动设置,我认为您基本上是在覆盖 properly-formatted Content-Type 请求 header 浏览器(根据 Fetch 规范要求)已经设置.