Node.js http - send GET data to server - javascript

How can I send data with GET method using https/http module? With POST everything works.
First code (GET):
var querystring = require('querystring'),
protocol = require('https');
var options = {
host: 'httpbin.org',
path: 'get',
method: 'GET',
headers: {},
port: 443
};
var data = querystring.stringify({
limit: 3
});
Object.assign(options.headers, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(data)
});
var req = protocol.request(options, response => {
response.setEncoding('utf8');
var end = '';
response.on('data', data => end += data);
response.on('end', () => console.log(end));
});
req.write(data);
req.end();
Response:
{
"args": {},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"origin": "31.0.120.218",
"url": "https://httpbin.org/get"
}
Second code (POST, I only replaced options object):
var options = {
host: 'httpbin.org',
path: 'post',
method: 'POST',
headers: {},
port: 443
};
Response:
{
"args": {},
"data": "",
"files": {},
"form": {
"limit": "3"
},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"json": null,
"origin": "31.0.120.218",
"url": "https://httpbin.org/post"
}
I will be very grateful for some help, now I don't know what I am doing wrong.

Your problem is that in a get, the query is appended to the path, as #Quy points out, get requests don't have a body. Without an understanding of how the server is set up, I would look at doing it like so:
var data = querystring.stringify({
limit: 3
});
var options = {
host: 'httpbin.org',
path: 'get?' + data,
method: 'GET',
headers: {},
port: 443
};

Related

Express render() doesn't work in post request

I am trying to do a redirect in a post request, but it doesn't work for me.
Here is the express.js code that should do it:
app.set('view engine','ejs');
app.use("/",express.static('public'));
app.post("/sendMovieData", async(req,res)=>{
console.log(req.body)
res.render("../view/movie-selected")
})
And also here is the fetch request.
let requestBody = {
"movieName": movie.getAttribute("data-movieName"),
"image": e.target.src,
"city": JSON.parse(localStorage.getItem("city_country")).city,
"country": JSON.parse(localStorage.getItem("city_country")).country
}
fetch('/sendMovieData', {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(requestBody)
});

Axios is not working to get access token?

i have axios call to get the bearer token it is oauth2.0 but for some reason it is failing same call is working in postman.
index.js
export async function getESLAccessToken(apiConfig: any) {
const _body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const _headers = {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
};
const request = {
method: 'POST',
_body,
headers: _headers
};
try {
const resp = await axios.post('https://auth/oauth2/token',
request);
console.log(resp.data);
} catch (err) {
// Handle Error Here
throw err;
}
}
This is how request building for axios
{
"method": "POST",
"_body": {
"grant_type": "client_credentials",
"client_id": "abc",
"client_secret": "xyz",
"scope": "APPPII APPPHI"
},
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
}
}
Error
Error: Request failed with status code 400
Postman working request and response
POST https://auth/oauth2/token
200
163 ms
POST /auth/oauth2/token HTTP/1.1
Headers
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Cache-Control: no-cache
Postman-Token: d90ccc33-1d77-4502-9a41-74080dd3d7a5
Host: qaapih8.corp.cvscaremark.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 163
Request Body
grant_type=client_credentials&client_id=abc&client_secret=xyz&scope=APPPII%20APPPHI
HTTP/1.1 200 OK
Response Body
{ "token_type":"Bearer", "access_token":"token returned", "expires_in":3600, "consented_on":164684, "scope":"APPPII APPPHI" }
The second argument of the axios.post function should be the request body. And the third argument should be the Axios request config object (Which you can set your headers). Axios POST Requests
In your case, the code should be like:
const body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const myHeaders = {
// add your headers here
}
const response = await axios.post(
'https://auth/oauth2/token',
body,
{ headers: myHeaders }
);
Replace
const request = {
method: 'POST',
_body,
headers: _headers
};
with:
const request = {
method: 'POST',
data: _body,
headers: _headers
};
As pointed out by the docs in the comments session: https://axios-http.com/docs/req_config

how to invoke a windows process using nodejs

I have a process running on my machine at port 8123, how can I invoke or call a windows process using nodejs..?
I tried using request
let bytes = new Buffer(xml, 'ascii')
var options = {
url: "https://" + host + ":" + port,
headers: {
'Content-Type': 'text/xml',
'Content-Length': Buffer.byteLength(bytes),
'Connection': 'keep-alive'
},
method: 'POST',
requestCert: true,
agent: false,
rejectUnauthorized: false
};
function callback(error, response, body) {
if (error) cb(error)
else cb(response)
}
request(options, callback);
but its returning with error code ECONNRESET and message assocket hang up
also tried HTTP like this
var options = {
host: '127.0.0.1',
port: port,
method: 'POST',
agent: false,
headers: {
'Content-Length': Buffer.byteLength(bytes),
'Content-Type': 'text/xml',
'Connection': 'keep-alive'
},
};
var req = http.request(options, function (res) {
res.on('data', function (chunk) {
cb('BODY: ' + chunk);
});
});
req.on('error', function (e) {
cb('problem with request: ' + e.message);
});
req.end();
this also returns the same error

I cannot view my JSON object in the console nor the terminal but I get a 200 status code

I am trying to get data points out of an API. I've used the authentication credentials and token to access and I get a status message 'ok' with a 200 code. I know I'm accessing but I cannot view the points nor stream any data in the terminal nor the console in the DOM.
1) I test this with Postman and I can get all the data in the terminal
method: 'GET',
url: 'https://www.url.io/rest/method/url-api/getDeviceData',
qs: { happy_token: 'eyJ0eXAiOiJKiOiJIUzI1NiJ9.ImlkfDM4ZDQ4OWM1LWI3YzUtNDE1Ni05ZWJlLWJmYzViMmJkODk1OXx0eXBlfHRpbWVzdGFtcHxpc0VuY3J5cHRlZHxvcmlnaW58MTAtMC0yOC0xODFfNTcwMDB8cG9saWN5fDHRsfGluYWN0aXZpdHlfdGhyZXNob2xkfDF8aXNUb2tlbnx1c2VybmFtZXxtb2hhbWVkLmZheWVkQHBkaWNvcnAuY29tfEd8NHwtMnw1fDZ8N3wkOHwkOXxIfEF8LTNdfEJ8JDl8SXxBfC0zXV18Q3wtMXxEfEVdIg.PaQdlILLK9lWN8zjmthTgWY_r77oBw' },
headers:
{
'cache-control': 'no-cache',
Connection: 'keep-alive',
'accept-encoding': 'gzip, deflate',
cookie: 'AWSALB=A+sdBzwAGrQmRer2y4ENHQgCc8TdDKiLHkM68CJMVKNhpVEBkiW53AhWSRKmzwk9scGKbSHeWtWL9YzuBayGFyWdkmkd5fkFSp2FYxbraW75UOoi8YtY',
Host: 'www.url.io',
'Postman-Token': '08e1668d-1f49-4451-a47e-61c9bae9df08,84944b9f-17eb-4520-88b2-344a7c46bdca',
'Cache-Control': 'no-cache',
Accept: '*/*',
'User-Agent': 'PostmanRuntime/7.13.0',
Authorization: 'Basic bW9oYW1lZC5ZEBwZGljb3JwLmNpAbWZheWVkMjk5OA=='
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
After I run npm start I get a beautifully JSON response:
"message": "Call successful",
"data": {
"device_id": {
"data": [
{
"parameters": {
"node_id": "1",
"ip_address": "172.00.00.00",
"tcp_id": "1"
},
"type": "P",
"mapping": "P",
"name": "P name",
"deviceName": "P name",
"path": "/profileView/devices/p name",
"deviceType": "P",
.
.
.
(etc)
This is what I want to get to!
However, when writing my code, as follows:
var credentials = function getCredentials() {
app.use(bodyParser.urlencoded({ extended: true }));
xhr.open("GET", URL, true, username, password);
xhr.withCredentials = true;
xhr.onreadystatechange = receiveResponse;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
xhr.open("POST", URL)
function receiveResponse(e) {
if (this.readyState == 4) {
if (this.status == 200) {
var response = this.responseXML
console.log(response);
}
}
}
}
function getToken(credentials) {
var data = response;
for (var i = 0; response[i]>1; I++) {
var results = response[i];
console.log(response[i]);
}
}
// server instance
const server = http.createServer((request, response) => {
response.end("hello azure");
console.log(response);
});
const port = process.env.PORT || 443;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
this is what I get in the terminal:
terminal response
Additionally, I can't see anything in the console log here:
Browser View
I feel like I am sending the right request but I cannot POST the data. Can anyone provide any insight? Thanks!

CoffeeScript: HTTPS Post to API, handle response

I'm new to CoffeeScript/JavaScript, but writing a script for Hubot to talk to my Ansible Tower API in Coffee. Below is my code so far:
module.exports = (robot) ->
robot.respond /deploy zabbix agent (.*)/i, (res) ->
host = res.match[1]
https = require 'https'
authbody = JSON.stringify({
username: "awx.api",
password: "example"
})
authrequest = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/authtoken/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
authrequest.end(authbody)
body = JSON.stringify({
limit: "#{host}"
})
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
request.end(body)
res.reply "Deploying zabbix agent to #{host}"
In the authrequest section, I post my username and password to the API and it should return in the response JSON in the following format:
{
"token": "8f17825cf08a7efea124f2638f3896f6637f8745",
"expires": "2013-09-05T21:46:35.729Z"
}
My questions is how I store the token to use as my authentication in the later requests.
You can store it in localStorage like so:
localStorage.setItem("token", "8f17825cf08a7efea124f2638f3896f6637f8745",);
and the get it when you make a request and insert in your header
const token = JSON.parse(localStorage.getItem('token'));
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
'Authorization': 'Bearer ' + token
}
})
request.on('response', function (response) {
response.on('data', function (chunk) {
let json = JSON.parse(chunk);
localStorage.setItem("token", json['token']);
});
});

Categories