NodeJS,Axios - 将文件从本地服务器发布到另一台服务器 [英] NodeJS, Axios - post file from local server to another server

查看:49
本文介绍了NodeJS,Axios - 将文件从本地服务器发布到另一台服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 端点,可以让客户端将他们的 csv 发布到我们的服务器,然后将其发布到其他人的服务器.我已经完成了我们的服务器部分,将上传的文件保存到我们的服务器,但我无法完成其他部分.我不断收到错误 { message: 'File not found', code: 400 } 这可能意味着文件永远不会到达服务器.我使用 axios 作为代理,有谁知道如何完成这项工作?谢谢.

I have an API endpoint that lets the client post their csv to our server then post it to someone else server. I have done our server part which save uploaded file to our server, but I can't get the other part done. I keep getting error { message: 'File not found', code: 400 } which may mean the file never reach the server. I'm using axios as an agent, does anyone know how to get this done? Thanks.

// file = uploaded file
const form_data = new FormData();
form_data.append("file", fs.createReadStream(file.path));
const request_config = {
    method: "post",
    url: url,
    headers: {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "multipart/form-data"
    },
    data: form_data
};
return axios(request_config);

更新

正如 axios 文档所述,我试图调用的 API 需要一个文件

As axios doc states as below and the API I'm trying to call requires a file

//data 是要作为请求体发送的数据//仅适用于请求方法PUT"、POST"和PATCH"//当没有设置 transformRequest 时,必须是以下类型之一://- 字符串、普通对象、ArrayBuffer、ArrayBufferView、URLSearchParams//- 仅浏览器:FormData、文件、Blob//- 仅节点:流、缓冲区

// data is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no transformRequest is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer

有什么办法可以让axios整体发送一个文件?谢谢.

Is there any way to make axios send a file as a whole? Thanks.

推荐答案

我认为 createReadStream 是您的问题,因为它是异步的.试试这个.由于 createReadStream 扩展了事件发射器,我们可以监听"事件发射器.什么时候结束/结束.

I'm thinking the createReadStream is your issue because its async. try this. Since createReadStream extends the event emitter, we can "listen" for when it finishes/ends.

var newFile = fs.createReadStream(file.path);

// personally I'd function out the inner body here and just call 
// to the function and pass in the newFile
newFile.on('end', function() {
  const form_data = new FormData();
  form_data.append("file", newFile, "filename.ext");
  const request_config = {
    method: "post",
    url: url,
    headers: {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "multipart/form-data"
    },
    data: form_data
  };
  return axios(request_config);
});

这篇关于NodeJS,Axios - 将文件从本地服务器发布到另一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆