我的任务是创建一个简单的功能,允许用户填写表格并为自己创建苹果钱包通行证(.pkpass)。我决定使用Pass2u。
我的问题是,在生成 .pkpass 文件后,我尝试调用 getPkpass,它在正文中返回一个流。我不知道如何使用它,并且发现了一个涉及某种在线读者的非常令人困惑的解释。目标是让整个事情像这样工作:
我正在寻求第 5 部分和第 6 部分的帮助,因为我已经可以创建文件并检索二进制流了。
以下是相关服务器代码:
const options = {
method: "GET",
headers: {
"x-api-key": "myAPIkey",
Accept: "application/vnd.apple.pkpass",
},
};
fetch(
`https://api.pass2u.net/v2/models/247901/passes/${response.data.passId}`,
options
)
.then((response) => {
console.log(response);
res.send(response);
})
.catch(function (error) {
console.log(
"An error occured occured while sending the GET request to pass2u"
);
console.error(error);
});
客户端处理如下:
axios
.post(
'http://localhost:80/generatePkpass',
{
name: `${qr.name} ${qr.lastName}`,
mobile: `${qr.phone}`,
email: `${qr.email}`,
qr: `${qr.output}`
},
{ responseType: 'blob', timeout: 30000 }
)
.then((response) => {
this.isGenerating = false
console.log(response)
console.log(response.data)
const blobUrl = URL.createObjectURL(response.data)
// Create an anchor element
const anchor = document.createElement('a')
// Set the href attribute to the blob URL
anchor.href = blobUrl
// Set the download attribute to specify the filename
anchor.download = 'yourPkPass.pkpass'
// Simulate a click on the anchor element
anchor.click()
// Clean up: revoke the temporary URL
URL.revokeObjectURL(blobUrl)
// const filename = 'yourpass.pkpass'
// saveAs(response.data, filename)
})
我知道客户端可能不应该将其作为 blob 处理,但我仍然认为服务器上存在问题。
伙计们,提前非常感谢,现在是凌晨 1 点,我感到非常疲惫。我是一名初学者开发人员,这是我在我工作的新公司的第一项任务。我因为不知道这一点而感到非常难过,但我被聘为前端开发人员,并且我一生从未使用过二进制字符串。
首先我在 axios 中对 pass2u api 进行了 GET 请求,但我将其更改为 fetch,这使事情变得清晰一些,但现在我仍然面临同样的问题,无法将 pass 发送到客户端。我还尝试在前端将其作为数组缓冲区进行处理,并且它下载了文件,但是,我无法在 safari 上打开它们
正如您所说,错误似乎出现在服务器端代码中,所以请尝试以下操作:
只需替换:
.then((response) => {
console.log(response);
res.send(response);
})
这样:
.then(passResponse => {
// Convert the response to a buffer
return passResponse.buffer();
})
.then(buffer => {
// Send the buffer back as a response
res.setHeader('Content-Type', 'application/vnd.apple.pkpass');
res.send(buffer);
})
在您的服务器端代码中。
您现有的客户端代码应该没问题。