WordPress загружает медиа через axios — Ошибка запроса 400 500

#node.js #wordpress #api #rest #axios

#node.js #wordpress #API #остальное #аксиос

Вопрос:

итак, всякий раз, когда я пытаюсь загрузить носитель (изображение jpg) с сервера node js с помощью axios, я получаю сообщение об ошибке, что запрос завершается ошибкой 400 или 500 в зависимости от различных кодов, которые я использовал, как описано ниже:

Для протокола, я сделал тот же запрос с теми же заголовками и телом от почтальона, и он всегда работает. Вот код, сгенерированный почтальоном для 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); });  

Теперь вот код, который я выполняю из узла 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)  

Однако, когда я делаю этот запрос, я получаю это:

 { “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" }  

Сравнивая оба, кажется, что есть проблема с файлом изображения, считываемым в узел, или что-то в этом роде. что вы, ребята, думаете?