简体   繁体   English

NodeJS:无法通过 Axios 发布表单数据

[英]NodeJS: Unable to post Form data via Axios

I am submitting form fields both via request and Axios .我通过requestAxios提交表单字段。 The request version works fine but not Axios one.请求版本工作正常,但不是 Axios 之一。 My guess is that I am not submitting data properly.我的猜测是我没有正确提交数据。 Sharing the both version共享两个版本

const data = {
        'CSRF': csrf,
        'anti-csrftoken-a2z': '',
        'offerListingID': offerListingID
}

Request Version which works fine, returns 3021 redirect请求版本工作正常,返回 3021 重定向

request({url:urlAddItem,headers:headers,method:'POST',gzip:true,form:data},(error:any,response:any,html:string) => {
                console.log(response.statusCode)
                if(!error && response.statusCode == 200) {
                    //
                }
            });

Axios Version which does not work, returns 200 Axios 版本不工作,返回200

const response = await axios({
                method: "post",
                url: urlAddItem,
                headers: headers,
                data:data
            });
            console.log(response.status )

I am unable to figure out where I am doing wrong.我无法弄清楚我在哪里做错了。

You will have to first convert your object to form data.您必须首先将 object 转换为表格数据。 You can use this function to do that你可以使用这个 function 来做到这一点

function createFormData(obj, form, namespace) {
  const formData = form || new FormData();
  for (const property in obj) {
    if (!obj.hasOwnProperty(property) || isUndefined(obj[property])) {
      continue;
    }
    const formKey = namespace ? `${namespace}[${property}]` : property;
    if (obj[property] instanceof Date) {
      formData.append(formKey, obj[property].toISOString());
    } else if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
      createFormData(obj[property], formData, formKey);
    } else {
      formData.append(formKey, obj[property]);
    }
  }
  return formData;
}

Then do然后做

await axios({
    method: "post",
    url: urlAddItem,
    headers: {"Content-Type": "multipart/form-data"},
    data: createFormData(data)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM