Javascript 检索照片,然后使用Axios将其发布到Foursquare签入
我正在尝试检索,然后使用in节点将JPEG图像发布到Foursquare的端点。我在Axios(和Postman)上尝试了几种方法,但总是收到相同的错误响应,即Javascript 检索照片,然后使用Axios将其发布到Foursquare签入,javascript,foursquare,axios,Javascript,Foursquare,Axios,我正在尝试检索,然后使用in节点将JPEG图像发布到Foursquare的端点。我在Axios(和Postman)上尝试了几种方法,但总是收到相同的错误响应,即缺少文件上传: { "meta": { "code": 400, "errorType": "other", "errorDetail": "Missing file upload", "requestId": "NNNNNNNNNNNNNNNNNNNNN" // not the true reque
缺少文件上传
:
{
"meta": {
"code": 400,
"errorType": "other",
"errorDetail": "Missing file upload",
"requestId": "NNNNNNNNNNNNNNNNNNNNN" // not the true requestId
},
"notifications": [
{
"type": "notificationTray",
"item": {
"unreadCount": 0
}
}
],
"response": {}
}
该图像使用Google静态地图API创建,并通过AxiosGET
请求检索:
const image = await axios.get(imageURL, {
responseType: "arraybuffer"
});
它被包装在一个async
函数中,并成功返回一个缓冲区。数据被读入缓冲区
,并转换为字符串:
const imageData = new Buffer(image, "binary").toString();
。我还尝试将字符串转换为base64
然后将该字符串POST
ed发送到Foursquare端点:
const postPhoto = await axios.post(
"https://developer.foursquare.com/docs/api/photos/add?
checkinId=1234&
oauth_token=[TOKEN]&
v=YYYYMMDD",
imageData,
{
headers: { "Content-Type": "image/jpeg" }
}
);
其中,checkinId
,oauth_令牌
和v
参数均有效
我尝试了不同的内容类型
值、base64
编码imageData
以及论坛和这里找到的其他几种解决方案(大多数都有好几年的历史了),但都不管用。响应errorDetail总是显示缺少文件上传
问题可能在于
POST
请求的结构,但我也可能请求/处理图像数据不正确。第二组(或第三组,或第四组)的眼睛来检查我把这些放在一起会非常有帮助 哎呀,我终于解决了这个问题
我最终通过邮递员得到了一些提示。以下是使用request
的邮差代码片段:
var fs = require("fs");
var request = require("request");
var options = { method: 'POST',
url: 'https://api.foursquare.com/v2/photos/add',
qs:
{ checkinId: [MY CHECKING ID],
public: '1',
oauth_token: [MY OAUTH TOKEN],
v: [MY VERSION] },
headers:
{ 'postman-token': '8ce14473-b457-7f1a-eae2-ba384e99b983',
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{ file:
{ value: 'fs.createReadStream("testimage.jpg")',
options: {
filename: 'testimage.jpg',
contentType: null
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
其中的关键部分是fs.createReadStream()
。我之前缺少的部分是将图像作为流传递给请求
使用此功能,我能够了解Axios请求:
const axios = require("axios");
const querystring = require("qs");
const FormData = require("form-data");
const getImageStream = async function(url) {
return await axios
.get(url, {
responseType: "stream"
})
.then(response => response.data);
};
let form = new FormData();
form.append("file", getImageStream([IMAGE URL]));
const requestURL = "https://api.foursquare.com/v2/photos/add";
const requestParams = {
checkinId: [MY CHECKIN ID],
public: 1,
oauth_token: [MY OAUTH TOKEN],
v: [MY VERSION]
};
const requestConfig = {
headers: form.getHeaders()
};
try {
const postPhoto = await axios.post(
requestURL + "?" + querystring.stringify(requestParams),
form,
requestConfig
);
return postPhoto;
} catch (e) {
console.error(e.response);
}
瞧,请求成功,图像被发布到Foursquare签入