I am trying to convert the below code which is using request module to axios module to send the POST request.
request module code:
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
var options = {
'method': 'POST',
'url': url,
'headers': {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Accept': 'application/json'
},
formData: {
'image': {
'value': imageFile,
'options': {
'filename': imgName,
'contentType': null
}
}
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log("SUCCESS");
});
The above code works fine and the image is posted successfully with the request module. But when I convert the same to axios, I am getting a 500 Error. (AxiosError: Request failed with status code 500)
axios module code:
const FormData = require('form-data')
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
const bodyFormData = new FormData();
bodyFormData.append("image['value']", imageFile);
bodyFormData.append("image['options']['filename']", imgName)
// bodyFormData.append("image['options']['contentType']", null)
console.log(bodyFormData)
const formHeaders = bodyFormData.getHeaders();
axios.post(url, bodyFormData, {
headers: {
...formHeaders,
'Cache-Control': 'no-cache',
'Accept': 'application/json',
}
}).then(function (response) {
console.log('SUCCESS');
}).catch(function (error) {
throw new Error(error);
});
Can anyone find out what I am doing wrong here?
Is there any other way to post the image using axios other than using form-data?
See the documentation for FormData#append(). You can provide extra data like the file name as the 3rd options parameter
const bodyFormData = new FormData();
// Pass filename as a string
bodyFormData.append("image", imageFile, imgName);
// or to specify more meta-data, pass an object
bodyFormData.append("image", imageFile, {
filename: imgName,
contentType: "image/jpeg",
});
axios.post(url, bodyFormData, {
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
...bodyFormData.getHeaders(),
},
});
Under the hood, request() does something very similar with the exact same form-data library. See request.js
Related
'react-native-image-picker' for uploading image in my application, Sometimes it is uploading and sometimes i am getting [TypeError: Network request failed] below is the code:
FormData in my component:
//image is :file:///data/user/0/com.testApp/cache/rn_image_picker_lib_temp_0d38d959-6ece-4750-a215-4b3f68002f4e.jpg
let formData = new FormData();
formData.append('images', { uri:image, name: imageSelected?.fileName, type: 'image/png' });
const response = await updateUserProfile(userDetails,formData)
Service call:
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: data,
});
return await response;
};
In Postman i have checked the api is working fine, What would be the problem in my code.
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: JSON.stringify(data),
});
return await response;
};
I'm trying to upload a photo on Google Photos, with google api, but i always get this error:
"status":{"code":3,"message":"Failed: There was an error while trying to create this media item."}}
I think that the problem is in the way i take the binary data of photo.
In this code i follow google photo api developers documentation, and it says, after take authorization, to:
1- Upload the raw bytes to a Google Server: to take upload-token
2- Use the upload token to create the media item.
This my node js code:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
'encoding': 'binary',
'flag' : 'r'
});
var url= 'https://photoslibrary.googleapis.com/v1/uploads';
var headers= {
'Authorization': 'Bearer '+token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-Content-Type': 'image/png',
'X-Goog-Upload-Protocol': 'raw',
'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
};
var body= photo
request({
url: url,
method:'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body)
}, function(error, response, body1){
if(error)
{
console.log(error);
}
else
{
var upToken = body1.toString();
console.log(upToken);
var url= 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate';
var headers= {
'Authorization' : 'Bearer '+token,
'Content-type': 'application/json',
};
var body= {
'newMediaItems': [
{
'description': 'Prague',
'simpleMediaItem': {
'fileName': 'prova',
'uploadToken': upToken,
}
}
]
};
request({
url: url,
method: 'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body),
}, function(error, response, body){
if(error)
{
console.log(error);
}
else
{
res.send(JSON.parse(body));
}
});
}});
Please help me, if anyone has any idea!!
How about this modification?
Modification points:
I think that encoding: "binary" is not required.
In this case, ``const photo = fs.readFileSync("fig1.png", { flag: "r" });andconst photo = fs.readFileSync("fig1.png");` can be used.
Please modify body: JSON.stringify(body) to photo of const photo = fs.readFileSync("fig1.png", { flag: "r" });.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
'encoding': 'binary',
'flag' : 'r'
});
var url= 'https://photoslibrary.googleapis.com/v1/uploads';
var headers= {
'Authorization': 'Bearer '+token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-Content-Type': 'image/png',
'X-Goog-Upload-Protocol': 'raw',
'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
};
var body= { 'media-binary-data': photo }
request({
url: url,
method:'POST',
headers: headers,
rejectUnauthorized: false,
body: JSON.stringify(body)
}, function(error, response, body1){
To:
const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", { flag: "r" });
var url = "https://photoslibrary.googleapis.com/v1/uploads";
var headers = {
Authorization: "Bearer " + token,
"Content-type": "application/octet-stream",
"X-Goog-Upload-Content-Type": "image/png",
"X-Goog-Upload-Protocol": "raw",
"X-Goog-Upload-File-Name": "2020-05-30T17:29:14+0000_0.png",
};
request(
{
url: url,
method: "POST",
headers: headers,
rejectUnauthorized: false,
body: photo,
},
function (error, response, body1) {
Note:
In this modification, it supposes that your token can be used for this API. Please be careful this.
When you want to directly put the uploaded image to an alubmn, please include albumId for requesting to https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate.
Reference:
Upload media
I can get the data by request from this code.
let request = require('request');
let options = {
'method': 'POST',
'url': 'https://example.com/api',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '12345678',
'client_secret': 'abcdefg'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?
const fetch = require("node-fetch");
const url = "https://example.com/api";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var data = JSON.stringify( {
'client_id': '12345678',
'client_secret': 'abcdefg'
});
fetch(url, {method: 'POST', headers: headers, body: data})
.then(response => response.json())
.then((resp) => {
console.log(resp);
})
.catch(error => console.error('Unable to fetch token.', error));
'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?
The documentation tells you how to encode data as form parameters.
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);
This is my function in NodeJs app which I am using to create user in openfire.
var createUser = function(objToSave, callback) {
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: objToSave
}
request(options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(error);
callback(error);
});
};
the objToSave is a json object contains username and password.
{
"Username": "gabbar",
"Password": "gabbar#123"
}
when i run this function i am getting the following error..
{
"statusCode": 400,
"error": "Bad Request"
}
I configured my secret-key properly and domain name is localhost://9090, can anybody tell me what I am doing wrong ? thanks in advance.
I think the options you provided needs JSON.stringify object before send it
The modified options is as below
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(objToSave)
}
I find out that problem was with request-promise. it was not properly sending data in the required format. so Instead of that now I am using different module minimal-request-promise. and It worked like charm for me. After using that, my code looks something like this.
var requestPromise = require('minimal-request-promise');
var createUser = function(objToSave, callback) {
const options = {
headers: {
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objToSave)
};
requestPromise.post('http://localhost:9090/plugins/restapi/v1/users', options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(options);
console.log(error);
callback(error);
});
};
I got an error every time when trying to POST data to the API.
Request:
changeUserAvatar(authParam, file) {
let formData = new FormData();
//file is actually new FileReader.readAsDataURL(myId.files[0]);
formData.append('profile_image', file);
fetch(BASE_URL + 'profile-image', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': authParam
},
body: formData
}).then((response) => {
return response.json();
}).then((response) => {
debugger;
}).catch((error) => {
console.error(error);
});
}
Error: profile_image can not be blank (422).
But it's not blank!
Request payload:
What do I do wrong?
Solved at GutHub: https://github.com/github/fetch/issues/505
I just had to leave Header without pointing any Content-Type manually.