Sending http request in node.js - http

I am trying to send a http request to a neo4j database using node.js. This is the code I am using:
var options = {
host: 'localhost',
port: 7474,
path: '/db/data',
method: 'GET',
headers: {
accept: 'application/json'
}
};
console.log("Start");
var x = http.request(options,function(res){
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
I check out that the database is running (I connect to the administration web page and everything is working). I am afraid that the problem is not on the database side but on the node.js side.
I hope some could give some light about this issue. I want to learn how to send a http request in node.js, the answer does not have to be specific to the neo4j issue.
Thanks in advance

If it's a simple GET request, you should use http.get()
Otherwise, http.request() needs to be closed.
var options = {
host: 'localhost',
port: 7474,
path: '/db/data',
method: 'GET',
headers: {
accept: 'application/json'
}
};
console.log("Start");
var x = http.request(options,function(res){
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
x.end();

I highly recommend to you use this minimal and easy package to send request on nodejs
Install package
npm install smoothly-request
Code that sends request
const smoothlyRequest = require('smoothly-request');
(async () => {
const result = await smoothlyRequest({
hostname: `http://localhost:7474`,
path: '/db/data',
method: 'GET'
});
})();

Related

Post multiple logs to DataDog with 1 HTTP request

I want to post multiple logs to DataDog from a JS function, using a single HTTP request. Looking at the v2 docs for DataDog's 'send logs' POST endpoint, it sounds like this is possible:
For a single log request, the API ... For a multi-logs request, the API ...
But it's not clear to me from the docs how to actually send a 'multi-logs' request. I've tried the following:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = {
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: ['My first production log.', 'My second production log.'],
service: 'my-service'
};
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
Perhaps unsurprisingly, this appears in DataDog as a single log with the following content:
[My first production log., My second production log.]
How can I achieve this?
Got it - this can be achieved by adding multiple log objects to the body like so:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = [{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My first production log.',
service: 'my-service'
},{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My second production log.',
service: 'my-service'
}];
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
(You'll probably want a loop instead of instantiating each log object separately.)

Strava authorization working on local host but not when published to azure

The following code authorizes my strava account in my web app:
function Authorize() {
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://localhost:44389/home/strava&response_type=code&scope=activity:read_all"
}
const codeExchangeLink = `https://www.strava.com/api/v3/oauth/token`
function codeExchange() {
fetch(codeExchangeLink, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: '#ViewBag.cId',
client_secret: '#ViewBag.cSec',
code: '#ViewBag.code',
//need to do this to get a new refresh token that 'reads all' and issues a new Access Token - refer to comments below
grant_type: 'authorization_code'
})
})
.then(res => res.json())
.then(res => getActivities(res))
}
However, when I publish to azure and change the document.location.href code and redirect address (as below) to match my published app it fails with a 'bad request' error.
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://xxxx.azurewebsites.net/home/strava&response_type=code&scope=activity:read_all"
Error is included below:
{"message":"Bad Request","errors":[{"resource":"Application","field":"redirect_uri","code":"invalid"}]}
Any help greatly appreciated
This was totally my error (embarrassingly). The issue was in my Strava Api App Settings, my call back uri was set to the default 'developers.strava.com'. All I had to do was change it to match my Published Web App uri 'xxxx.azurewebsites.net/home/strava' and it now works.

ClientFunction: _axios2 is not defined

I'm running TestCafe for UI automation, using ClientFunctions to trigger API requests (so that I can pass along session cookies).
Currently I have a ClientFunction with fetch which works fine... except we're now testing IE 11 and Fetch is unsupported.
Fetch code:
const fetchRequestClientFunction = ClientFunction((details, endpoint, auth, method) => {
return window
.fetch(endpoint, {
method,
credentials: 'include',
headers: new Headers({
accept: 'application/json',
'Content-Type': 'application/json',
}),
body: JSON.stringify(details),
})
.then(httpResponse => {
if (httpResponse.ok) {
return httpResponse.json();
}
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
However when I try to switch it to axios... not so much:
import axios from 'axios';
const axiosRequest = ClientFunction((details, endpoint, auth, method) => {
return axios({
method,
auth,
url: endpoint,
data: details,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 3000,
})
.then(httpResponse => {
if (httpResponse.status < 300) return httpResponse;
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
Tried using window.axios, and also passing axios as a dependency. I've also tried making the axios request without the ClientFunction... and despite getting response of 200, the website wasn't updated as expected.
Each time I either get _axios2 is not defined or window.axios is not a function. I would greatly appreciate some guidance here.
TestCafe ClientFunctions allow only serializable objects as dependencies. You need to have axios on the client side to send such a request.

Hubot with slack adapter - cannot perform rtm.start

I'm trying to have hubot + slack on my local machine.
installed hubot and slack client.
running:
bin\hubot -a slack
and got error (after adding log messages to the script)
INFO Connecting...
INFO { ok: false, error: { [Error: socket hang up] code:
'ECONNRESET' } }
from reading code in node_modules\slack-client\src\client.js
found the problem occurs in a POST request:
Client.prototype.login = function() {
this.logger.info('Connecting...');
return this._apiCall('rtm.start', {
agent: 'node-slack'
}, this._onLogin); };
Client.prototype._apiCall = function(method, params, callback) {
var options, post_data, req;
params['token'] = this.token;
post_data = querystring.stringify(params);
options = {
hostname: this.host,
method: 'POST',
path: '/api/' + method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
req = https.request(options);
tried to do: Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
with no success

Doing http requests through a SOCKS5 proxy in NodeJS

I'm planning to do a series of HTTP requests in NodeJS though Tor.
Tor uses SOCKS5 so I went out and searched for a way to proxify HTTP requests in NodeJS.
I'm planning to the the default http.request() function to do the work. However, I can't seem to find a way to use a proxy with that. Someone suggested that I could do this:
var http = require("http");
var options = {
host: "localhost",
port: 9050,
path: "http://check.torproject.org",
method: 'GET',
headers: {
Host: "http://check.torproject.org",
}
};
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
But it didn't work.
So, any suggestions?
I've just published two modules that should help you do this: socks5-http-client and socks5-https-client.
Just use those instead of the default http module. The API is the same. For example:
require('socks5-http-client').request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
I know I'm answering an old question but there is a better solution available for this question, about how to use sock4 & sock5 proxy in Node.js. For the sake of simplicity, I will be using request-promise module however you can also use bare request module.
Requrement: socks-proxy-agent, request-promise
Example:
async function main() {
var proxy = "socks4://1.2.3.4:35618"
var agent = new SocksProxyAgent(proxy);
var options = {
uri: 'http://targetUrl',
agent: agent,
headers: {
'User-Agent': 'Request-Promise'
}
}
try {
var responce = await rp(options)
} catch(err) {
console.log(err)
}
console.log(responce) }
Not a complete answer, but you may want to keep your eye on these two modules.
https://github.com/Ayms/node-Tor
Support is being added into: https://github.com/Ayms/node-bot.
I sent him an email asking when he expected this to be complete, will update this post soon with that information.
I had the same problem and used polipo as proxy between node and TOR
node (request) - polilp httproxy:8123 - polipo - tor (socks5:9050).
For mac (osx with brew) it worked like this:
brew install polipo tor
tor # start top
polipo socksParentProxy=localhost:9050 # start polipo
Working example with request
var request = require('request');
var options = {'url':'https://check.torproject.org/', 'proxy':'http://localhost:8123'}
request(options,
function (error, response, body) {
if (error){
console.log(error);
return;
}
var usingTor = (body.indexOf('Congratulations. This browser is configured to use Tor.') !== -1);
expect(usingTor).to.equal(true);
});
If you're on *nix machine, you can use tsocks. It will "socksify" the whole process so you can use it even for anything which does not support proxies at all. This article has some great examples
Basically it's as easy as doing tsocks node myscript.js. I am not sure if it works with tsocks npm start but you could give it a try (npm starts your code as a subprocess)
All you need is some setup first (put server = 127.0.0.1 to etc/tsocks.conf)
Yo should try with polipo, that work for me;
http://ccm.net/faq/805-installing-an-easy-http-proxy-cache-polipo

Resources