Node.js - POST request won't execute until end of script - javascript

I'm trying to perform multiple POST requests in my code however the POST request will only occur when the script terminates. So far I've loaded the below code in via a function and imported the function as a module with no success.
I'm relatively new to node.js so I may be missing something obvious here. Does anyone have any ideas?
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://XXXXXXXXXX.com/Example',
'headers': {
'Authorization': 'Basic SuperSecretPassword',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'To': Receiver,
'From': Sender,
'Parameters': '{"Flag":"1","Duration":"5"}'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
console.log(options);

Related

Cascading two scripted API requests togethor

I am trying to check endpoint availability by cascading two api requests and passing first request's response(token) into another in authorization header field. Although the token is getting generated, the second api is not capturing the correct token in the 'token' variable. Let me know scripting error am making. Is there a way to print my authorization field value?
Output of the script is as below:
{
"error": "Invalid token."
}
401
AssertionError [ERR_ASSERTION]: Expected 200 response
Code:
var assert = require('assert');
var request = require('request');
var options2,token,info;
var options = {
'method': 'POST',
'url': '1',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '*',
'client_secret': '**',
'grant_type': 'client_credentials'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
info = JSON.parse(response.body);
console.log(info.access_token);
token=info.access_token;
});
var request = require('request');
var options2 = {
'method': 'GET',
'url': '***',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
}
};
request(options2, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
console.log(response.statusCode);
assert.ok(response.statusCode == 200, 'Expected 200 response');
});
Move the call
request(options2, function (error, response),
inside the callback function of request 1, along with options2.
Since request 1 call (token one) can take some time your request 2 will be fired while you still haven't received response for token call. You can also use Async/Await to make it more clear, since callbacks makes things hard to read.

get value from previous request and pass to another request in nodejs

I have a scenario where I am trying to get the parsed json response of the variable from the below POST request which I want to store in a variable and pass again to the next GET request in the headers. The approach that I am trying now doesn not give the expected results, Is there anything wrong here how should be my approach here to get the expected results, any help is appreciated.
PS : I am new to nodejs
var request = require('request');
var headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Basic Y2Y6',
'Connection': 'keep-alive',
'Content-Length': '95',
'User-Agent': 'python-requests/2.22.0',
'content-type': 'application/x-www-form-urlencoded'
};
var dataString = 'grant_type=password&username=userpp&password=Password';
var options = {
url: 'https://testurl/oauth/token',
method: 'POST',
headers: headers,
body: dataString
};
let ab;
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body);
var parsedBody = JSON.parse(body)
//console.log(parsedBody["access_token"])
ab = parsedBody["access_token"];
}
}
request(options, callback);
var headers1 = {
'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
'Authorization': `'bearer ' ${ab}`
};
var options1 = {
url: 'https://testurl1.com?getdata=user',
method: 'GET',
headers: headers1
};
function callback1(error1, response1, body1) {
if (!error1 && response1.statusCode == 200) {
console.log(body1);
}
}
request(options1, callback1);
The problem here is that you're running asynchronous code but treating it synchronously
You see, when you call request(options, callback); and then request(options1, callback1); inline like that, by the time the second request runs, the first callback hasn't happened yet
One way to get around this: put the second request INSIDE the first callback function.
Big brain time: use the request-promise library and learn how to make requests using promises and chaining .then() callbacks.
Humungous brain time: learn how to use async/await features as another nicer way to interact with promises

Header section has more than 10240 bytes (maybe it is not properly terminated)

I'm using NodeJs to try to upload an attachment to a Jira Issue via the Jira Rest API.
The api expects multipart/form-data so this is how I'm calling it in Node:
function uploadAttachments(supportFormData, callback) {
const url =
'https://somewhere.com/jira/rest/api/2/issue/' +
supportFormData.issueId +
'/attachments';
var options = {
url: url,
headers: {
Authorization: { user: username, password: password },
'X-Atlassian-Token': 'nocheck'
}
};
var r = request.post(options, function(err, res, body) {
if (err) {
console.error(err);
callback(false);
} else {
console.log('Upload successful! Server responded with:', body);
callback(false);
}
});
var form = r.form();
form.append('file', supportFormData.attachments[0].contents, {
filename: supportFormData.attachments[0].fileName,
contentType: supportFormData.attachments[0].contents
});
}
The error I'm receiving is:
org.apache.commons.fileupload.FileUploadException: Header section
has more than 10240 bytes (maybe it is not properly terminated)
The "supportFormData.attachments[0].contents" is ofType Buffer.
Any suggestions as to what could be causing this error?
I ran into this same issue and it turns out JIRA (or Java) requires \r\n as new line character. After I changed \n to \r\n my requests went through without problem.
If its a basic auth change options object to
let auth = new Buffer(`${username}:${password}`).toString('base64');
var options = {
url: url,
headers: {
Authorization: `Basic ${auth}`,
'X-Atlassian-Token': 'nocheck'
}
};

Request keeps on getting Error code: 400 - can someone please have a look on what I'm doing wrong?

Spent a few hours trying to solve this but keep on getting 400 errors. I think my payload is incorrect but not sure what I need to do.
I've tried the same request in POSTMAN with great success, and also have tried different combinations on formatting my payload (body).
I've also tried the following: var body = {"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}};
function main(){
// Set the headers
var headers = {
'Authorization': 'Bearer ya29.GlyvBPhT4Y502Yo4NZ6sKI001AYlVU6om5ytXrzf2vjfEYERrsdMSBu-2ZkKir83jjj06-ewqYuBvvrx8mKfuTW1YjjlmtPmRdlK0I0Gjx',
'Content-Type': 'application/json',
'User-Agent': 'Untitled browser'
}
var uri = 'https://language.googleapis.com/v1/documents'+encodeURI(':analyzeSentiment');
var form = JSON.stringify({"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}});
// Configure the request
var options = {
url: uri,
method: 'POST',
headers: headers,
form: form
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
else{
console.log('Error code: '+response.statusCode)
}
})
}
main();
Update - this is how it works in POSTMAN
Header is the same too:
Solved!
Need to post as body rather than form

Post request from Scheduled Job is not working

(I am new to JS, node.js and Heroku so I hope the question is clear)
I have an Heroku node.js app, I was able to set up Heroku scheduler to run a task every 1 hour.
The task runs on time and the method fireHook() is called (I can see the log in the console) but the request does not work (I don't get any lo or error).
This is the job:
#!/usr/bin/env node
var request = require('request')
function fireHook(){
console.log("firing")
request({
url: 'https://XXXXXX.herokuapp.com/jobs',
method: "POST",
headers: { "content-type": "application/json" },
json: {"user_id":{ "id":"ddddd"}}
}, function(error, response, body) {
console.log(response)
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
} else {
console.log('success: ', body)
reportToSnitch()
}
})
}
fireHook();
process.exit();
2 questions:
Why sold the request not working ?
I am currently using a webhook to call my main app, is there a better way to call a function on the main app from the script directly?
Thanks
I think your process.exit() is killing your script before the request has received its response. Try to move it into the callback:
#!/usr/bin/env node
var request = require('request')
function fireHook(){
console.log("firing")
request({
url: 'https://XXXXXX.herokuapp.com/jobs',
method: "POST",
headers: { "content-type": "application/json" },
json: {"user_id":{ "id":"ddddd"}}
}, function(error, response, body) {
console.log(response)
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
} else {
console.log('success: ', body)
reportToSnitch()
}
process.exit();
})
}
fireHook();
JavaScript is asynchronous so you have to be careful to consider where and when certain events will occur. If your reportToSnitch() function is async as well, you may need to fire the process.exit() at the end of that function.

Categories