Post file as raw body in AXIOS NodeJS. I tried many ways to achieve this but none of them worked.
What i have tried ?
var file = fs.readFileSync("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg").toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg",{encoding:"utf8"}).toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg");
file = Buffer.from(file).toString('utf8')
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.createReadStream("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
But none of them worked as i wanted.
Actual working example from JQuery AJAX in Browser
var fileupload = $("#inpFile")[0];
var file = fileupload.files[0];
$.ajax({
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
type: 'POST',
success: function (response) {
DisplayMessage(response);
},
data: file,
contentType: false,
processData: false
});
Have you tried setting the content-type header?
Per Talg123 I found that if you set contentType to false in jQuery it might be equivalent to multipart/form-data.
client side:
async function main(){
try{
const buffer = new ArrayBuffer(8);
const data = new FormData();
const blob = new Blob([buffer],{type : 'multipart/form-data'});
data.append('data', blob);
const options = {
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
method: 'POST',
headers: { 'content-type': 'multipart/form-data' },
data
};
let result = await axios(options);
console.log(result);
}catch(e){
console.error("error",e);
}
}
main()
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
server side per https://github.com/axios/axios/issues/1006#issuecomment-584840380
const axios = require('axios');
const FormData = require('form-data');
// Where buffer is a file
formData.append('file', buffer);
// Added a promise version like seen in earlier comments to get this
const contentLength = await formData.getLength();
await axios(`<ENDPOINT>`, {
method: 'POST',
baseURL: <BASE_URL>,
params: {
fileName: '<FILE_NAME>.png'
},
headers: {
authorization: `Bearer <TOKEN>`,
...formData.getHeaders(),
'content-length': contentLength
},
data: formData
});
js fiddle for image/jpeg
https://jsfiddle.net/bn7yLh61/
Related
Can you please help me convert the following request to axios request.
const request = require('request-promise');
const data = {name:'pte', age:30}
const options = {secret:'34444'}
const opp = {
method: 'POST',
uri: 'https://something',
headers: { 'content-type': 'application/json' },
options,
body: JSON.stringify(data),
};
return request(opp);
const axios = require('axios')
const url = 'https://something'
const data = { name : 'pte', age : 30 }
const options = {
headers : {
'content-type' : 'application/json'
}
}
axios.post(url, data, header)
I am trying to send a POST request with body as form-data since this seems to be the only way that works.
I tried this in Postman too and sending body as raw JSON didn't work.
So I tried doing the same with node-fetch but seems like body is being sent as JSON and I'm getting the same error as before (when using raw from Postman).
try{
const { streamId } = request.body;
const headers = {
"Authorization": INO_AUTHORIZATION_CODE,
// "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>"
"Content-Type": "application/json"
}
const url = `https://www.inoreader.com/reader/api/0/stream/contents/${streamId}`;
const body = {
AppId: INO_APP_ID,
AppKey: INO_APP_KEY
}
const resp = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
// body: body,
headers: headers
});
const json = await resp.text();
return response.send(json);
} catch(error) {
next(error);
}
Only setting body as form-data works:
You need to use the form-data package as mentioned in their doc
so your code will be
const FormData = require('form-data');
const form = new FormData();
form.append('AppId', INO_APP_ID);
form.append('AppKey', INO_APP_KEY);
const resp = await fetch(url, {
method: 'POST',
body: form
});
Usar:
const form = new URLSearchParams();
form.append('AppId', INO_APP_ID);
form.append('AppKey', INO_APP_KEY);
The following Imgur Upload API isn't working: *https://api.imgur.com/3/upload
*. Any idea what else I can use or if they got a new one? I looked at the docs, but couldn't find anything although I might be missing something here: https://apidocs.imgur.com/?version=latest
Here's the code I use to upload images to imgur. The endpoint is different, I don't know if yours work.
const uploadImg = function(file: any) {
// Begin file upload
console.log("Uploading file to Imgur..");
var apiUrl = 'https://api.imgur.com/3/image';
var apiToken = <your-token>;
var settings: any = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
mimeType: 'multipart/form-data'
};
var formData = new FormData();
formData.append("image", file);
formData.append("album", "your-album-name"); // optional
settings.data = formData;
return axios(apiUrl, {
method: 'post',
data: formData,
headers: {Authorization: 'Bearer ' + apiToken,
Accept: 'application/json'}});
}
I am trying to make a post request on url https://test.cashfree.com/api/v2/subscription-plans using node js requests but getting this body in return:
{"status":"ERROR","subCode":"400","message":"Invalid JSON in request body"}
This is my Code:
var querystring = require('querystring');
var request = require('request');
var form = {
planId: "NJGRKON12354",
planName: "Rent Product",
type: "PERIODIC",
amount: 100,
intervalType: "month",
intervals: 1
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'X-Client-Id': 'XXXXX',
'X-Client-Secret': 'XXXXXX',
'Content-Type': 'application/json'
},
uri: 'https://test.cashfree.com/api/v2/subscription-plans',
body: formData,
method: 'POST'
}, function (error1, res1, body) {
console.log('statusCode:', res1.statusCode);
console.log("Body: ", body);
});
When i try with same headers and body in postman its Running.
Postman Hit
I am receiving http POST response OK 200, but I see no file present on JIRA issue. From my research I can understand that it could be some problem with formData I am sending with request. Below is my code:
var newBuffer = new Buffer(req.Payload, 'base64');
var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
frequency: 10, // in milliseconds.
chunkSize: 2048 // in bytes.
});
// With a buffer
myReadableStreamBuffer.put(newBuffer);
var formData = {
'file': {
'content': myReadableStreamBuffer,
'filename': req.FileName,
'mimeType': req.MimeType //mimeType from JSON
}
};
var options = {
url: 'https://comapny.atlassian.net/rest/api/2/issue/' + req.ReferenceId + '/attachments',
method: "POST",
json: true,
headers: {
'ContentType': 'multipart/form-data',
'Authorization': 'Basic ' + new Buffer(config.jira.jiraUser.userName + ':' + config.jira.jiraUser.password).toString('base64'),
'X-Atlassian-Token': 'nocheck'
},
formData: JSON.stringify(formData)
};
request(options,
function (error, response, body) {
if (error) {
errorlog.error(`Error Message : PostAttachmentToCSMS : ${error}`);
return response.statusCode;
}
else {
successlog.info(`Attachment posted for issue Key: ${req.ReferenceId} ${response.statusMessage}`);
return response.statusCode;
}
});
I can write file from myReadableStreamBuffer, so that seems ok. Please help me to identify the problem. Many thanks!
After spending some more time on it, I have found the correct format for formData:
var newBuffer = new Buffer(req.Payload, 'base64');
var formData = {
file: {
value: newBuffer,
options: {
filename: req.FileName,
contentType: req.MimeType
}
}
};
For whom like me getting errors with this API.
After struggling so many hrs on this thing, I finally found this works like a charm. I've got "XSRF check failed" 403/404 error message before writing this code.
// Don't change the structure of formData.
const formData = {
file: {
value: fs.createReadStream(filepath),
options: {
filename: filename,
contentType: "multipart/form-data"
}
}
};
const header = {
"Authentication": "Basic xxx",
// ** IMPORTANT **
// "Use of the 'nocheck' value for X-Atlassian-Token
// has been deprecated since rest 3.0.0.
// Please use a value of 'no-check' instead."
"X-Atlassian-Token": "no-check",
"Content-Type": "multipart/form-data"
}
const options = {
url: "http://[your_jira_server]/rest/api/2/issue/[issueId]/attachments",
headers: header,
method: "POST",
formData: formData
};
const req = request(options, function(err, httpResponse, body) {
whatever_you_want;
};
I was able to post attachments to JIRA using axios in the following way:
const axios = require('axios');
const FormData = require('form-data')
const fs = require('fs');
const url = 'http://[your_jira_server]/rest/api/2/issue/[issueId]/attachments';
let data = new FormData();
data.append('file', fs.createReadStream('put image path here'));
var config = {
method: 'post',
url: url,
headers: {
'X-Atlassian-Token': 'no-check',
'Authorization': 'Basic',
...data.getHeaders()
},
data: data,
auth: {
username: '',
password: ''
}
};
axios(config)
.then(function (response) {
res.send({
JSON.stringify(response.data, 0, 2)
});
})
.catch(function (error) {
console.log(error);
});