How to set https proxy - javascript

How on earth do I use an https proxy with http2 in nodejs. I've tried looking around and I can't find any info on it. Take for example the following code:
const client = http2.connect('https://twitter.com');
const req = client.request({':method': 'GET', ':path': '/', ':authority': 'twitter.com', ':scheme': 'https', 'Cookie': loadCookies(cookiejar) });
req.setEncoding("utf8");
var body = "";
req.on('response', (responseHeaders) => {
storeCookies(responseHeaders, cookiejar);
});
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () =>{
client.destroy();
});
So how would I go about routing this request through a proxy, say for example Charles where the proxy would be set 127.0.0.1:8888.

Related

Implementing CoAP protocol on node.js

Do you know any guides or tutorials about implementing CoAP protocol connection on node.js? I have to implement simple server and client application. I've checked all the resources I've found, including of course their documentation:
https://github.com/mcollina/node-coap
but it is still unclear for me.
Thank you for any help.
EDIT:
If this is implementation of server, how should look client like?
var coap = require('coap')
, server = coap.createServer()
server.on('request', function(req, res) {
res.end('Hello ' + req.url.split('/')[1] + '\n')
})
// the default CoAP port is 5683
server.listen(function() {
var req = coap.request('coap://localhost/Matteo')
req.on('response', function(res) {
res.pipe(process.stdout)
res.on('end', function() {
process.exit(0)
})
})
req.end()
})
or like this , an example for coap client
const coap = require('coap'),
bl = require('bl');
//construct coap request
var req = coap.request({
observe: false,
host: '192.168.0.93',
pathname: '/',
port: 5683,
method: 'get',
confirmable: 'true',
retrySend: 'true',
//query:'',
options: {
// "Content-Format": 'application/json'
}
})
//put payload into request
var payload = {
username: 'aniu',
}
req.write(JSON.stringify(payload));
//waiting for coap server send con response
req.on('response', function(res) {
//print response code, headers,options,method
console.log('response code', res.code);
if (res.code !== '2.05') return process.exit(1);
//get response/payload from coap server, server sends json format
res.pipe(bl(function(err, data) {
//parse data into string
var json = JSON.parse(data);
console.log("string:", json);
// JSON.stringify(json));
}))
});
req.end();
It should be like this:
const coap = require('coap')
req = coap.request('coap://localhost')
console.log("Client Request...")
req.on('response' , function(res){
res.pipe(process.stdout)
})
req.end()
Source: https://github.com/mcollina/node-coap/blob/master/examples/client.js

Http GET Request from NodeJS to external API with http.get()

I am trying to do an HTTP GET request to an external API with NodeJS (using Express), but I am not getting any data back. My code is the nextone:
import * as http from "http";
const options = {
host: "EXAMPLE.COM",
path: "/MY/PATH",
headers: {
"Content-Type": "application/json",
"Authorization": "Basic XXXXXXXXXXXXXXXXXX"
}
};
const req = http.get(options, function(res) {
console.log("statusCode: " + res.statusCode);
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
But the response I get is:
statusCode : 302 and BODY is empty.
The external API works properly (I have tried doing a http GET Request with INSOMNIA and returns data)
The request I am doing NEEDS an Authorization Token
What am I doing wrong? or what can I do to get the data back?
Cheers
You are just throwing data to console.log and not responding to request.
You did not mention if what http server you are using with node. In case you are using express.js (most common one) you should have something like:
const express = require("express");
const app = express();
const port = 3003;
const http = require("http");
// your webserver url localhost:3003/fetch-something
app.get("/fetch-something", (req, res) => {
const options = {
host: "EXAMPLE.COM",
path: "/MY/PATH",
headers: {
"Content-Type": "application/json",
Authorization: "Basic XXXXXXXXXXXXXXXXXX"
}
};
const httpReq = http.get(options, function(httpRes) {
//output status code to your console
console.log("statusCode: " + httpRes.statusCode);
httpRes.on("data", function(chunk) {
// still nothing happens on client - this will also just print to server console
console.log("data", chunk);
// return some data for requested route
return res.send(chunk);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

How to send HTTP Request in node js under proxy

Following node js code works well and get all the required results.
But when i run the code in the computer under proxy settings defined. It doesnt give the result.
var options: https.RequestOptions = {
host: item.hostname,
port: +item.port,
path: item.path,
method: 'POST',
headers: newHeader
}
var req = https.request(options, function(res){
if(res.statusCode !== 200){
//reject();
//return;
}
var result = '';
res.setEncoding('utf8');
res.on('data', function(chunk){
result += chunk;
});
res.on('end', function(){
resolve(result);
});
res.on('error', function(e){
reject(e);
});
});
How to enable proxy support in http module requests in NODE JS that it checks if there is any proxy defined and perform that enabled request.
options data in debug mode :
headers:Object
Accept:"application/json;api-version=3.0-preview.1"
Content-Length:104
Content-Type:"application/json"
host:"marketplace.visualstudio.com"
method:"POST"
path:"/_apis/public/gallery/extensionquery"
port:0
The proxy should be the host/port and the path is the final path of the request that the proxy should make (host:port/path).
Basically e.g. if making a request through a proxy on localhost:8888:
path = host + path, host = 'localhost', port = 8888;

How to post data from my html page to a listener?

I'm currently designing a UI for an Automated Parking System. I currently need to test if my page sends out data from a form by sending it to a listener. I currently have this code but I'm not sure why it isn't working. Any help would be greatly appreciated.
This is my code that sends the data to a local listener.
<script>
var INPARK = {cardID: $("#ticket_num").val(), lift: 1, floor: 1};
$.ajax({
type:"POST",
url: '192.168.150.148:5007',
contentType:"application/json",
data: JSON.stringify(INPARK)
});
</script>
This is the listener code.
var HOST = '192.168.150.148'; // This should be your IP of 192.168.150.XXX
var PORT = 5007;
var http = require('http');
http.createServer(function (req, res) {
// Only listen for POST requests
if (req.method === 'POST') {
var buffer = '';
req.on('data', function (chunk) {
buffer += chunk;
});
req.on('end', function () {
var path = req.url.substring(0, req.url.indexOf('/', 1)).toUpperCase();
var json;
try {
json = JSON.parse(buffer);
} catch (err) {
//
}
if (path === '/INPARK') {
// Handle INPARK request
console.log(json);
res.write('inpark results');
} else if (path === '/OUTPARK') {
// Handle OUTPARK request
console.log(json);
res.write('outpark results');
} else {
// Do nothing - Bad request
res.write('BAD REQUEST');
}
// Close the connection
res.end();
});
}
}).listen(PORT, HOST, function () {
console.log('Listening at %s:%s', HOST, PORT);
});
Your ajax request is most likely going from port 80 or 443 to 5007, which is a cross domain request, hence it will fail,
If you want to resolve this issue, read up on CORS:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing,
and JSONP:
https://en.wikipedia.org/wiki/JSONP

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