WordPress uploading media through axios - Request error 400 500

Viewed 346

so, whenever I'm trying to upload media (a jpg image) from a node js server using axios, I'm getting an error that the request is failing with either error 400 or 500 depending on different codes I used as elaborated below:

For the record, I made the same request with the same headers and body from postman and it is always working. Here is the code as generated by postman for axios:

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('file', fs.createReadStream('/C:/Users/.........jpg'));
data.append('title', 'YOOOO');
data.append('description', 'SMALL IMAGE');

var config = {
  method: 'post',
  url: 'https://........./wp-json/wp/v2/media',
  headers: { 
    'Content-Type': 'image/jpeg', 
    'Authorization': 'Bearer ...............', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

Now here is the code that I'm executing from node js:

const media_data = new FormData();
  media_data.append('file', fs.createReadStream('C:/Users/..............jpg'));
  media_data.append('title', 'YOOOO');
  media_data.append('description', 'SMALL IMAGE');

  const config_media = 
  {
    method: 'post',
    url: 'https://......./wp-json/wp/v2/media',
    headers: 
    { 
      'Content-Type': 'image/jpeg',
      'Authorization': `Bearer ${jwt_token}`,
    },
    data: media_data
  };

  // Make request
  const response_media = await axios(config_media)
  const media_info = response_media.data
  console.log(media_info)

However, when I'm making this request, I'm getting this:

{
“code”: “rest_upload_sideload_error”,
“message”: “Sorry, this file type is not permitted for security reasons.”,
“data”: {
“status”: 500
}

I even tried replacing createReadStream with readFileSync and same error. Now, you may have noticed that I omitted one line from the postman code which is ...data.getHeaders(), but when I included that line, I got:

{
    "data": {
        "code": "rest_upload_no_data",
        "message": "No data supplied.",
        "data": {
            "status": 400
        }
    },
    "headers": {
        "Allow": "GET, POST"
    },
    "status": 400
}

After some testing I came up with this:

const create_media = await axios({
    url: 'https://......./wp-json/wp/v2/media',
    method: 'POST',
    headers: {
      'Content-Disposition':'attachment; filename="file.jpg"',
      'Authorization': `Bearer ${jwt_token}`,
      'Content-Type':'image/jpeg'
      },
    data: fs.readFileSync('C:\\.......test.jpg')
  })

Now, this code is working perfectly fine, the image gets uploaded. However, doing it this way, means I'm only passing the image and a second request has to be made to update the media with additional information like title, description, caption etc...which I'm doing right now and which works but I would rather have one request to handle this. If postman is able to send the image plus the additional information all in one request, why is it not working when I'm doing it from node js? Is there anything I'm doing wrong or missing from my code above? Please let me know. Thank you.

P.S Here is the header of a successful request from postman:

{
    "accept": "*\/*",
    "accept_encoding": "gzip, deflate, br",
    "authorization": "Bearer ***HIDDEN***",
    "connection": "keep-alive",
    "content_type": "multipart\/form-data; boundary=--------------------------268674632138594510244294",
    "content_length": "82305",
    "host": "***HIDDEN***.com",
    "user_agent": "PostmanRuntime\/7.28.4",
    "content_disposition": "attachment; filename="file.jpg"",
    "postman_token": "***HIDDEN***"
}

and here is the request header of the failed request (error 400):

{
    "accept": "application\/json, text\/plain, *\/*",
    "accept_encoding": "gzip, deflate, br",
    "accept_language": "en-US",
    "authorization": "Bearer ***HIDDEN***",
    "content_type": "multipart\/form-data; boundary=--------------------------318043908548597415066605",
    "content_length": "17",
    "host": "***HIDDEN***.com",
    "user_agent": "Mozilla\/5.0 ***HIDDEN***",
    "content_disposition": "attachment; filename="file.jpg"",
    "sec_fetch_site": "cross-site",
    "sec_fetch_mode": "cors",
    "sec_fetch_dest": "empty"
}

Comparing both, it does seem there's an issue with the image file being read into node or something like that. what do you guys think?

0 Answers
Related