Getting Invalid JSON in request body everytime - node.js

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

Related

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

POST File in AXIOS NodeJs

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/

Nodejs Post attachment to JIRA

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);
});

Implementing request.postAsync promise with bluebird

I am using the bluebird promises framework to make a POST request and get the response to that POST request:
var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
var options = [];
var scores = [];
// Configure the request
options[0] = {
url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1',
method: 'POST',
headers: headers,
form: {'apikey': 'XXXXXXXXXXX', 'text': 'I love dogs'}
}
// Start the request
request.postAsync(options[0]).spread(function(response, body) {
if (response.statusCode == 200) {
var answer = JSON.parse(body);
scores[0] = answer['aggregate']['score'];
}
}).then(function() { console.log(scores[0]) });
This is the error message that I am getting:
Unhandled rejection TypeError: expecting an array or an iterable object but got [object Null]
at apiRejection (/Users/vphuvan/demos/node_modules/bluebird/js/release/promise.js:10:27)
etc.
What do I have to do to resolve this error message?
Note: the version of bluebird I am currently using is 3.0.5
You need to set multiArgs: true in bluebird 3. This is one of the changes in the promisify API of bluebird 3.
Full solution below.
var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'), { multiArgs: true });
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
var options = [];
var scores = [];
// Configure the request
options[0] = {
url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1',
method: 'POST',
headers: headers,
form: {'apikey': 'XXXXXXXXXXX', 'text': 'I love dogs'}
}
// Start the request
request.postAsync(options[0]).spread(function(response, body) {
if (response.statusCode == 200) {
var answer = JSON.parse(body);
scores[0] = answer['aggregate']['score'];
}
}).then(function() { console.log(scores[0]) });
Here is an answer that works: use the 'request-promise' framework. I am using request-promise#1.0.2, which is based on bluebird#2.10.2. Clearly, something undocumented happened between bluebird#2.10.2 and bluebird#3.0.5
var rp = require('request-promise');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
var options = [];
var scores = [];
var text = 'I love dogs';
// Configure the request
options[0] = {
url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1',
method: 'POST',
headers: headers,
form: {'apikey': 'XXXXXXXXXX', 'text': text}
}
// Start the request
rp(options[0])
.then(function (body) {
// POST succeeded...
console.log(body);
var answer = JSON.parse(body);
scores[0] = answer['aggregate']['score'];
})
.then(function() { console.log(scores[0]); })
.catch(function (err) {
throw err
});

use GET method in node js request?

i want to pass data with GET method in node js , my response is ok but in php file $_GET is empty. what is wrong?
var querystring = require('querystring');
var req = require('request');
var form = {
number: 'test',
msg: 'test',
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
req({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://localhost:8080/sms/index.php',
body: formData,
method: 'GET'
}, function (err, res, body) {
console.log('res is',res);
console.log('err',err);
});
An HTTP GET request cannot have a request body. $_GET parses parameters from the query string. The headers Content-Lengthand Content-Type do not make sense for a GET request as they apply to the body of the request, which GET cannot have. You need to use the qs option instead of body.
req({
uri: 'http://localhost:8080/sms/index.php',
qs: form,
method: 'GET'
}, function (err, res, body) {
//
});

Resources