[英]Node - POST local file to remote endpoint using AXIOS
我在獲取 NodeJS 服務器上的本地文件並將其上傳到 web 端點時遇到了一些麻煩。 我不斷收到錯誤:
AxiosError:在 IncomingMessage.handleStreamEnd(D:\myproject\node_modules\axios\dist\node\ axios.cjs:2712:11) 在 IncomingMessage.emit (node:events:539:35) 在 endReadableNT (node:internal/streams/readable:1345:12) 在 processTicksAndRejections (node:internal/process/task_queues:83:21) ) { 代碼: 'ERR_BAD_REQUEST',
我不完全確定我做錯了什么。 我寫了很多帖子,似乎正確地構建了我的 AXIOS 帖子請求?
try {
const fileStream = await fs.createReadStream('./pathtofile.ext');
let formData = new FormData();
formData.append('myFile', fileStream, 'pathtofile.ext');
axios.post('https://my.endpoint.com', formData, {
headers: {
...formData.getHeaders(),
}
})
.then(res => res.data)
.catch( err => console.log(err))
} catch(err) {
console.error(err)
}
我有點不知所措,因為我似乎無法弄清楚這么簡單的任務我做錯了什么? 當我調用“getHeaders()”時,標題似乎也是正確的,它顯示“ 'content-type': 'multipart/form-data;
”
感謝您提供的所有幫助!
我不確定您為什么要嘗試使用 ReadStream 讀取文件,因為您需要將整個文件發布到您的端點。
使用 ReadStream 的好處是在讀取文件時執行操作。 因此,對於文件的每一塊,您都需要做一些事情。
在這種情況下,我相信您需要做的就是讀取文件然后觸發您的 POST 請求。
您可以使用readFileSync而不是createReadStream來做到這一點。
您的代碼在這個方向上應該是 go:
try {
const fileContents = await fs.readFileSync('./pathtofile.ext',{encoding: 'the-right-encoding'});
let formData = new FormData();
formData.append('myFile', fileContents, 'pathtofile.ext');
axios.post('https://my.endpoint.com', formData, {
headers: {
...formData.getHeaders(),
}
})
.then(res => res.data)
.catch( err => console.log(err));
} catch(err) {
console.error(err)
}
這樣, await關鍵字會更有意義,因為您將等待 readFileSync promise 解析。
請務必選擇正確的編碼來讀取文件。
此外,由於您使用的是 Axios,因此您可以通過向 post 方法提供回調 function 來檢查上傳狀態。
const onUploadProgress = (event) => {
const percentage = Math.round((100 * event.loaded) / event.total);
console.log(percentage);
};
首先,您應該 go 到像Reqbin這樣的站點並模擬請求以確保您的 web 端點不是問題所在。 我不厭其煩地用我自己的端點測試了您的代碼,它運行良好。 大多數時候,此類問題是由於授權、速率限制或類似問題引起的。 如果我知道端點的類型,也許我可以提供幫助。 祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.