transform $.get to node.js request - javascript

i'm using geolocation, i was handling everything on client side, now I wat to handle this from
Currently using it as;
var url = "youtube.com",
options = {
key: API_KEY,
video: "vid_id"
};
$.get(url, options, function(data) {
console.log(data)
})
I want to use it with nodeJS HTTPS, so i tried;
var https = require("https"),
url = "youtube.com",
options = {
key: API_KEY,
video: "vid_id"
};
https.get(url, options, function(data) {
console.log(data)
})
but i cant get it work I hope someone can convert this.

Try using the request module for node.js. Install it by running:
npm install request.
var request = require('request');
request(`youtube.com/?key=${key}&video=${video_id}`, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('body:', body); // Print body of the response.
});

Related

Twitter API streaming request returning 401

I am using Twitter for Node.js to make requests to the Twitter API, but I keep getting 401 Error which according to Twitter Docs means that there was an issue authenticating the request.
I am using the example from the twitter npm page:
const Twitter = require('twitter');
function twitter() {
var TwitterClient = new Twitter({
consumer_key: 'MY_KEY',
consumer_secret: 'MY_SECRET',
bearer_token: 'MY_TOKEN'
});
try {
TwitterClient.stream('statuses/filter', {
track: 'javascript'
}, function(stream) {
stream.on('data', function(event) {
console.log(event && event.text);
});
stream.on('error', function(error) {
try {
throw error;
}
catch (err) {
console.log(err);
}
});
});
} catch(e) {}
}
I get the following error in console:
Failed to load resource: the server responded with a status of 401 ()
Doing the GET request from the twitter npm page works fine:
var params = {screen_name: 'nodejs'};
TwitterClient.get('statuses/user_timeline', params, function(error, tweets, response) {
if (!error) {
console.log(tweets);
}
});
What I've tried:
Regenerated new tokens and double-checked them
Checked for updated system hour
Added access tokens and access secret to authentication
Thank you for your help

api proxy server not parsing data back to user CORS

I am trying to access an api but when I access it in the browser, I get a CORS error. To get around this problem I set up an api proxy server. When this proxy gets a html request it connects to the browser blocked api and pulls the data needed. I think there is a problem on the proxy server where it is also blocking CORS and that needs to be changed, I’m not so sure. When I call the proxy api it gets the data from the browser blocked api and logs it to the console but does not push it to the browser because of the error below.
1.How do I correct this error “Reason: CORS header 'Access-Control-Allow-Origin' missing”
2.Should I be doing this a different way?
Error
Data being logged on the server
Server routing code - app.js
const apiCallFromRequest = require('./Request')
const apiCallFromNode = require('./NodeJsCall')
const apiCallFromTEST = require('./test.js')
const http = require('http')
http.createServer((req, res) => {
if(req.url === "/test"){
let start_time = new Date().getTime();
apiCallFromTEST.callApi(function(response){
//console.log(JSON.stringify(response));
res.write(JSON.stringify(response));
console.log(response);
console.log("Request API Requested");
console.log('API Test Time:', new Date().getTime() - start_time, 'ms');
res.end();
});
API proxy rought code -test.js
var rp = require('request-promise');
const callExternalApiUsingRequest = (callback) => {
var options = {
uri: 'https://app.invoiceninja.com/api/v1/products',
headers: {
'X-Ninja-Token': 'APIKEY'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (data) {
console.log(data);
return callback(data);
})
.catch(function (err) {
// API call failed...
});
}
module.exports.callApi = callExternalApiUsingRequest;
website side - Just a basic fetch request
function gotProductData(){
fetch('http://localhost:3000/test')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Try to install "cors" package (npm install cors) and import to app.js :
const cors = require('cors');
Run that above routes:
app.use(cors())
More details:
https://www.npmjs.com/package/cors#installation

MYSQL + Node.JS Post Request Confusion

I am very new to networking and I have this code which, when I use a REST API like Postman, does exactly what I want it to do:
router.post('/', function(req,res,next){
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function(err, conn){
if(err)
{
console.error('SQL Connection error: ', err);
return next(err);
}
else
{
var query = conn.query("INSERT INTO coordinates (id,lat,lon) VALUES(3,2,1);");
if(err)
{
console.error('SQL error: ', err);
return next(err);
}
res.json("Coordinates sent.");
}
})
} );
That is, it sends the query request to the MYSQL database. My question is, how do I do this without using Postman to send the POST request?
Thank you.
You can't unless you make a post request from within your application or something. If you don't intend on sending data, you can just make it a GET request by changing
router.post('/', function(req,res,next){
to
router.get('/', function(req,res,next){
Then you can just go to the relevant URL from your browser. If you're using chrome and you just wanna see the JSON data, I'd also recommend installing the JSONView chrome extension.
EDIT
Here's the example request using request-promise
var request = require('request-promise');
var objectData = {
name: 'Bruce',
alias: 'Batman'
};
var options = {
method: 'POST',
uri: 'http://your.api/endpoint/',
body: objectData,
json: true // Automatically stringifies the body to JSON
};
request(options).then(function(response){
// handle success response
}, function(error){
// handle error response
})

Hapi.js Proxy - change the response before reply

I'm trying to test Hapi.js for a new project I'm working on
My goal is to trigger a request on my Hapi server and this request will trigger another request on a remote server using Hapi proxy, and the response will be only specific properties from the remote response
To test this a request to /api/type3/name must be made which will invoke an API call to GitHub's API to get the user object
Code:
server.route({
method: 'GET',
path: '/api/type3/{name}',
handler: {
proxy: {
mapUri: function(request,callback){
callback(null,'https://api.github.com/users/'+request.params.name);
},
onResponse: function(err, res, request, reply, settings, ttl){
console.log(res);
reply(res);
},
passThrough: true,
xforward: true
}
}
});
The response from the above code is the response object from GitHub
Now I need to save this response so I can manipulate it and return only what I need
But when I debug the response object it contains a lot of data and I can't find the response payload inside of it
So how to extract only the response from GitHub from the response object ?
Thanks a lot
The res object is an http.IncomingMessage. If you want to work with the body of the response you need to read all the data off it first.
You have 2 choices for doing this.
1) Vanilla Node
onResponse: function(err, res, request, reply, settings, ttl){
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log(body);
reply(body);
});
}
2) Using Wreck (a module for working with HTTP in Node made by the Hapi folks)
var Wreck = require('wreck');
onResponse: function(err, res, request, reply, settings, ttl){
Wreck.read(res, null, function (err, payload) {
console.log(payload);
reply(payload);
});
}
In the wreck case above, you could do
payload = payload.toString();
To convert the buffer to actual data.
I want to load xml data from remote server and convert the response to json.
This thread helped me lot to find a solution that worked for me. But in my case the code above doesn't worked too, because the response from the remote server was gzipped. In my console there were only unreadable data.
I tried to enable automatic payload parsing for the proxy but it was not successful. Finally i had to unzip the response by myself with 'zlib'.
This code is working for me:
'use strict'
const url = require('url')
const h2o2 = require('h2o2')
const Hapi = require('hapi')
const parseString = require('xml2js').parseString
var zlib = require('zlib')
const _ = require('lodash')
var remoteServerUrl = 'http://some-url.com:2434'
var originUrl = 'http://localhost:3000'
// Create a server with a host and port
const server = new Hapi.Server()
server.connection({
host: 'localhost',
port: 3001,
routes: {
cors: {
origin: [originUrl],
},
},
})
server.register({
register: h2o2,
}, function (err) {
server.start(function (err) {
console.log('Proxy Server started at: ' + server.info.uri)
})
})
server.route({
method: '*',
path: '/proxy/{path*}',
config: {
payload: {
// parse: true, // didn't worked for me
// parse: 'gzip', // didn't worked for me
output: 'stream',
},
},
handler: {
proxy: {
passThrough: true,
timeout: 15000,
acceptEncoding: false,
mapUri (request, callback) {
callback(null, url.format({
protocol: url.parse(remoteServerUrl).protocol,
host: url.parse(remoteServerUrl).host,
port: url.parse(remoteServerUrl).port,
pathname: request.params.path,
query: request.query,
}))
},
onResponse (err, res, request, reply, settings, ttl) {
if (err) {
console.error('Hapi server error: ', err)
}
// let's unzip the response
var gunzip = zlib.createGunzip()
var xmlStr = ''
gunzip.on('data', function (data) {
xmlStr += data.toString()
})
gunzip.on('end', function () {
// do something with the string
// in this case convert xml to json string
parseString(xmlStr, {}, function (err, result) {
// send result back
reply(result)
})
})
res.pipe(gunzip)
},
},
},
})
Maybe this helps someone else ;)

Add parameters to HTTP POST request in Node.JS

I've known the way to send a simple HTTP request using Node.js as the following:
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/foo.html'
};
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
I want to know how to embed parameters in the body of POST request and how to capture them from the receiver module.
Would you mind using the request library. Sending a post request becomes as simple as
var options = {
url: 'https://someurl.com',
'method': 'POST',
'body': {"key":"val"}
};
request(options,function(error,response,body){
//do what you want with this callback functon
});
The request library also has a shortcut for post in request.post method in which you pass the url to make a post request to along with the data to send to that url.
Edit based on comment
To "capture" a post request it would be best if you used some kind of framework. Since express is the most popular one I will give an example of express. In case you are not familiar with express I suggest reading a getting started guide by the author himself.
All you need to do is create a post route and the callback function will contain the data that is posted to that url
app.post('/name-of-route',function(req,res){
console.log(req.body);
//req.body contains the post data that you posted to the url
});
If you want to use the native http module, parameters can be included in body this way:
var http = require('follow-redirects').http;
var fs = require('fs');
var options = {
'method': 'POST',
'hostname': 'example.com',
'path': '/foo.html',
'headers': {
},
'maxRedirects': 20
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
var postData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"examplekey\"\r\n\r\nexamplevalue\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--";
req.setHeader('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
req.write(postData);
req.end();

Categories