axios POST request to strapi image upload [Internal Server Error] - reactjs

I'm uploading an image to strapi using axios but the response is 500 error. However in Postman the request is 200
POSTMAN
AXIOS CODE
let bodyFormData = new FormData();
bodyFormData.append('files', this.state.avatar, this.state.avatar.name)
bodyFormData.append('ref', 'user')
bodyFormData.append('refId', getId())
bodyFormData.append('field', 'avatar')
bodyFormData.append('source', 'users-permmissions')
axios({
method: 'post',
url: `${strapi}/upload`,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${withToken()}`,
},
data: bodyFormData,
}).then(res=>console.log(res.data)).catch(err=>{console.log(err.response.data.message)})
what's supposed to be the issue here?
Here's part of the strapi user model
{
"avatar": {
"model": "file",
"via": "related",
"plugin": "upload",
"required": false
}
}

The solution is to throw Axios in the trash. I struggled with this for a day of my life that I will never get back. There's a longish, years-old thread at https://github.com/axios/axios/issues/318 with people complaining about being unable to get multipart form uploads to work with Axios.
I switched to the request-promise module and got it to work within minutes, using the following simple code:
const fs = require("fs-extra");
const rp = require('request-promise');
let out = await rp({
method: 'POST',
uri: 'http://mystrapihost/upload',
formData: {
// Like <input type="text" name="ref">
'ref': "customer", // name of the Strapi data type, singular
'field': "attachments", // a field named "attachments" of type "Media"
'refId': "838e238949ewhd82e8938299e289e99", // strapi ID of object to attach to
// Like <input type="file" name="files">
"files": { // must be called "files" to be "seen" by Strapi Upload module
name: "myfile.pdf",
value: fs.createReadStream("/path/to/myfile.pdf"),
options: {
filename: "myfile.pdf",
contentType: 'application/pdf'
},
},
},
headers: {Authorization: 'Bearer myjwtgobbledygook123456'} // put your JWT code here
});
console.log(out);
Enjoy!!

Related

React JS CORS-ORIGIN - Instagram Basic Display API

I have problem with CORS: Access-Control-Allow-Origin when try to exchange the code for access token from Instagram API.
Instagram API documentation Step 5 : https://developers.facebook.com/docs/instagram-basic-display-api/getting-started#step-5--exchange-the-code-for-a-token
Body parametars:
const body = {
'client_id': 'xxxxxxxxxxxxxx',
'client_secret': 'xxxxxxxxxxxxxx',
'grant_type': 'authorization_code',
'redirect_uri': 'https://localhost:3000/',
'code': instaCode
};
My request:
axios.post(`https://api.instagram.com/oauth/access_token`, qs.stringify(body), {
headers: {'content-type': 'application/x-www-form-urlencoded'}
});
Đ¢his code worked 2 months ago.
edit: you can try this axios post request to send form data first which seems better, below worked for me though
That won't work, you have to send the body in a form data.
I believe fetch API would work but that's available since node 17, if you're using earlier version this is what worked for me.
SOURCE https://www.section.io/engineering-education/integrating-instagram-basic-display-api/
const { post } = require("request");
const { promisify } = require("util");
const postAsync = promisify(post);
const form = {
client_id: NUMBER,
client_secret: STRING,
grant_type: "authorization_code",
redirect_uri: STRING,
code: req.body.code,
};
let { body, statusCode } = await postAsync({
// let result = await postAsync({
url: "https://api.instagram.com/oauth/access_token",
form,
headers: {
"content-type": "multipart/form-data",
host: "api.instagram.com",
},
});
npm i request
and use that inside a try/catch of course

Mailgun Attachment + Axios

I would like to send an attachment with Mailgun using react+axios.
Currently, I get an email with an attachment, but it is not named correctly (the name is ".") and if I rename it to a text file it contains the text "[object Object]".
Do you have any idea how to solve this problem?
const form = new FormData();
const fs = require("fs");
form.append("from", "example#gmx.ch");
form.append("to", "Bob <example#hotmail.ch>");
form.append("subject", "Test");
form.append("text", "Hello!!");
form.append("attachment", [{
filename: "example.txt",
data: fs.readFileSync(__dirname + "/text.txt", {
encoding: "utf8",
flag: "r"
})
}]);
const endpoint = "https://api.mailgun.net/v3/sandbox123.mailgun.org/messages";
await axios.post(endpoint, form, {
auth: {
username: "api",
password: process.env.MAILGUN_API_KEY
},
headers: { "Content-Type": "multipart/form-data" }
});
Two things:
As per the mailgun docs when sending attachments you must use "multipart/form-data" encoding. Try:
await axios.post(endpoint, form, {
auth: {
username: "api",
password: process.env.MAILGUN_API_KEY
},
headers: { 'Content-Type': 'multipart/form-data' }
});
Try putting your attachment object inside an array. I am not familiar with the mailgun API but I saw a couple examples where the attachments were inside an array, maybe even if there is a single attachment the API is still expecting it this way.

can i send form-data with axios with delete request in react?

i need send this request with axios.
i need header as multipart request, like below
headers: {
"Content-type": "multipart/form-data",
},
I used spring boot for backend. It expect maltipart not application/json. I tried below code, But it not worked for multipart.
axios.delete(URL, {
headers: {
Authorization: authorizationToken
},
data: {
source: source
}
});
Thanks a lot #Sinan Yaman. I generated it using POSTMAN. Answer is
var axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('keyName', 'project/photoes/1613388881570-note1.txt');
var config = {
method: 'delete',
url: 'localhost:8080/storage/deleteFile',
headers: {
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Typically before make frontend we test our backend with postman. For any type of frontend http calls code can automatically generate using postman. This is awesome feature of POSTMAN. Follow below steps.
Press the code button
Select the your backend code environment

Spotify WebPlayer API - Change Player Request

I've been working on a Spotify player using React, and so far I've been able to get the player to properly connect to the API and receive a device_id.
My next step is change the player to the newly "made" one, but I keep on receiving 400: Required field device_ids missing, even though I have it included in the PUT request:
const requestOptions = {
method: 'PUT',
headers: {
'Authorization' : 'Bearer ' + spotifyAccessToken
},
data: {
"device_ids": [device_id],
"play": 'true'
}
};
// Change player
fetch('https://api.spotify.com/v1/me/player', requestOptions)
Am I missing something/formatting it incorrectly? I've tried changing the data to body and I instead get a 400: Malformed JSON.
Thanks in advance!
I was able to get this working using the following format:
const requestOptions = {
method: 'PUT',
body: JSON.stringify({
device_ids: [southORadioDevId],
play: 'true'
}),
headers: {
Authorization: `Bearer ${spotifyAccessToken}`
},
};
// Change player
fetch('https://api.spotify.com/v1/me/player', requestOptions)

How to do an API call to Google Cloud Vision TEXT_DETECTION on Expo React Native

I am trying to do an API call to Google Cloud Vision. What should my request body look like?
I tried reading the documentation on how to format the request body but I am not getting any luck.
This is my request body
let image = this.fileToBase64().done();
let body = JSON.stringify({
requests: [
{
image: {
content: image
},
features: [
{ type: "TEXT_DETECTION", maxResults: "5"},
]
}
]
});
This is my call
let response = await fetch("https://vision.googleapis.com/v1/images:annotate?key=" + GOOGLE_API_KEY, {
method: "post",
body: body,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
}
);
I am expecting a complete response in JSON with status code 200 but instead I am getting the response JSON with message "Request must specify image and features." and status code 400
Seems the problem was that the image content was empty as I did console.log(image). I just added the let image = await this.fileToBase64().done(); s the fileToBase64 is async

Resources