proxy with hapi.js and h2o2, connection close - proxy

I try to configure hapi.js to proxy requests from /{params*} path to http://localhost:3000. It works fine for root '/' but when I try call /login I receive Cannot GET /login and on request I can see 'GET /login HTTP/1.1\r\nHost: localhost:3000\r\nConnection: close\r\n\r\n'. On my UI server http://localhost:3000/login works fine.
this is my proxy configuration
proxy: {
mapUri: (request, callback) => {
//loaded from a configuration file
let url = `http://localhost:3000${request.path}`;
callback(null, url);
}
}
Anyone know how to configure hapi proxy to pass custom routes?

Acctually it started to work. This is my current route
{
method: 'GET',
path: '/{param*}',
config: {
handler: {
proxy: {
mapUri: (request, callback) => {
let tls = conf.ui.tls;
let host = conf.ui.host;
let port = conf.ui.port;
let url = `${tls ? 'https://' : 'http://'}${host}:${port}${request.path}`;
callback(null, url);
}
}
}
}
}

Related

Nuxt Proxy changes POST to GET when proxy is set to true

In my universal nuxt app, I have setted proxy at true and rewritte my url to avoid CORS issue.
But when I'm setting proxy to true, all my post requests are changed to get request. Don't understand why and how to configure it no to have this transformation.
Here is my nuxt.config.js :
/*
** Axios module configuration
*/
axios: {
proxy: true
},
proxy: {
'/apicore/': { target: 'http://blablabla.fr', pathRewrite: { '^/apicore/': '' }, changeOrigin: true }
}
My call:
async createJoueur({ state, dispatch, commit }, data) {
const URL = '/apicore/joueur'
await this.$axios
.post(
URL,
data, {
headers: {
'Content-Type': 'application/json'
}
}
)
.then((response) => {
console.log('JOUEUR LOGGED : ')
if (response.status === 200) {
} else {
console.log('Login failed / Not found')
}
}
)
.catch((error) => {
console.log('ERROR')
})
With this proxy set to true, my post-call becomes a get one.
Do I have forgotten something in my configuration?
Thanks for your help.
I was with the same problem! i solved it using changeOrigin: false.
I know that it must be the default value (Look at changeOrigin session ),
but it seems like in nuxtjs proxy implementation this value default is true (Look at Options session) .
I had the same issue and after some logging using the onProxyReq option I found out that the issue was the Cloudflare proxy, not the nuxt proxy. Cloudflare was forwarding HTTPS requests to HTTP and this forces POST requests to become GET requests as is common with 301/302 redirects.
As far as I know, it's not possible to configure Cloudflare to do 308 redirects, which would not alter the HTTP method/body.

Hapijs proxy : subdomain routing to maindomain/subdomain

main domain : "mymain.com"
sub domain : "subdomain.mymain.com"
when i get call from subdomain.mymain.com , i would need to display in browser contents from mymain.com/somepath/subdomain.
i would like to use proxy options in hapi-js and do the above . But with
code like
config: {
handler: function(request, reply) {
let hostValue = request.headers.host;
let path = request.params.path;
let subdomain = hostValue.split('.')[0];
return reply.proxy({
uri: 'http://mymain.com/somepath/subdomain'
});
} \/\/end of handler
} //end of config
i am not able to achieve it . Just page is empty. This is angular based project and angular route does not get executed for this.
But if do for url : subdomain.mymain.com the below
return reply.proxy({
host: 'mymain.com',
port: 80,
protocol: "http"
});
It works fine. Any clue how get this subdomain issue resolved?
In your example, you're not placing the value of subdomain into the url, change it to look like this:
config: {
handler: function(request, reply) {
let hostValue = request.headers.host;
let path = request.params.path;
let subdomain = hostValue.split('.')[0];
return reply.proxy({
uri: 'http://mymain.com/somepath/'+subdomain
});
} \/\/end of handler
} //end of config
Changing this line:
uri: 'http://mymain.com/somepath/subdomain'
to this:
uri: 'http://mymain.com/somepath/'+subdomain
Alternatively, to clean up a bit, you could try using the mapUri config option of h2o2. Something like this:
server.route({
method: 'GET',
path: '/',
handler: {
proxy: {
mapUri: function (request, callback) {
let hostValue = request.headers.host;
let subdomain = hostValue.split('.')[0];
console.log('proxying for', subdomain)
callback(null, 'http://mymain.com/somepath/'+subdomain);
}
}
}
});

SignalR not working with DelegatingHandler

We have a delegating-handler that catches requests with a certain url prefix, and then reroutes them behind the firewall with the fed auth cookie attached...
This is working for our WebApi layer, but SingalR is firing off requests on its own while it is trying to connect that doesn't follow the pattern... I can't figure out how to force it to use the proper url prefix.
This is the url that is generated from the post request when it is trying to do long-polling: https://localhost:44330/signalr/connect?transport=longPolling&
See that it hasn't put the '/qsixlsignalr' into the url, which my delegating handler will be looking for.
var signalRBaseURL = "/qsixlsignalr"
$(function () {
// http://stackoverflow.com/questions/15467373/signalr-1-0-1-cross-domain-request-cors-with-chrome
$.support.cors = false;
var connection = $.hubConnection(signalRBaseURL);
var myHub = connection.createHubProxy('xlHub');
myHub.on('notify', function (message) {
alertsViewModel.refreshActiveCount(localStorage.getItem(PROJECT_ID));
if (window.location.pathname == '/' || window.location.pathname == '') {
alertsViewModel.refresh(localStorage.getItem(PROJECT_ID));
}
toastr.success(message);
});
connection.disconnected(function () {
setTimeout(function () {
connection.start();
}, 3000);
});
connection.logging = true;
connection.start();
});
If I remember correctly you need to tell SignalR explicitly that you don't want to use the the default url
var connection = $.hubConnection(signalRBaseURL, { useDefaultPath: false });

http to https node proxy

I would like to know the easiest way to set up a proxy where I can make HTTP requests in (i.e.) localhost:8011 and the proxy makes a HTTPS request in localhost:443 (the HTTPS answer from the server should be translated to HTTP by the proxy as well)
I'm using node.js
I've tried http-proxy like this:
var httpProxy = require('http-proxy');
var options = {
changeOrigin: true,
target: {
https: true
}
}
httpProxy.createServer(443, 'localhost', options).listen(8011);
I have also tried this:
httpProxy.createProxyServer({
target: {
host:'https://development.beigebracht.com',
rejectUnauthorized: false,
https: true,
}
}).listen(port);
But when I'm trying to connect I'm getting this error
/Users/adrian/Development/beigebracht-v2/app/webroot/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:103
var proxyReq = (options.target.protocol === 'https:' ? https : http).reque
^
TypeError: Cannot read property 'protocol' of undefined
I would like to do it with node, but, other solutions can be valid.
(The proxy will be used in localhost just with testing purposes so security is not a problem)
I needed a HTTP->HTTPS node proxy for unit testing. What I ended up doing was creating the HTTP proxy and then have it listen for and handle the connect event. When the server receives the CONNECT request, it sets up a tunnel to the HTTPS target URL and forwards all packets from the client socket to the target socket and vice versa.
Sample code:
var httpProxy = require('http-proxy');
var net = require('net');
var url = require('url');
var options = {
host: 'localhost',
port: 3002
};
var proxy = httpProxy.createProxyServer();
proxy.http = http.createServer(function(req, res) {
var target = url.parse(req.url);
// The `path` attribute would cause problems later.
target.path = undefined;
proxy.web(req, res, {
target: target
});
}).listen(options.port, options.host);
// This allows the HTTP proxy server to handle CONNECT requests.
proxy.http.on('connect', function connectTunnel(req, cltSocket, head) {
// Bind local address of proxy server.
var srvSocket = new net.Socket({
handle: net._createServerHandle(options.host)
});
// Connect to an origin server.
var srvUrl = url.parse('http://' + req.url);
srvSocket.connect(srvUrl.port, srvUrl.hostname, function() {
cltSocket.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n'
);
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});

How can I send an AJAX request to a node.js server via HTTPS?

I have the following node.js server set up listening to port 9001
var https = require('https');
var fs = require('fs');
var qs = require('querystring');
var options = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
console.log('Request Received!');
console.log(req.method);
if (true || req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
console.log(body);
var POST = qs.parse(body);
console.log(POST);
});
}
res.end("hello, world\n");
}).listen(9001);
and I am trying to get this server to respond to an AJAX call
function form_save()
{
console.log("submitted!");
var data_obj = {
data1: "item1",
data2: "item2"
}
$.ajax({
url: 'https://adam.testserver.com:9001/',
type: "POST",
dataType: "json",
data: data_obj,
success: function() {
console.log("success!");
},
complete: function() {
console.log("complete!");
}
});
}
There are two problems occurring with my arrangement. The first is that if I start the server and then click the button that triggers my form_save() the node server does not respond and I get the following error:
submitted!
OPTIONS https://adam.testserver.com:9001/ Resource failed to load
jQuery.extend.ajaxjquery.js:3633
$.ajaxjquery.validate.js:1087
form_savew_worksheet.php:64
confirm_deletew_worksheet.php:95
jQuery.event.handlejquery.js:2693
jQuery.event.add.handlejquery.js:2468
w_worksheet.php:73
complete!
At this point if I access that url directy (https://adam.testserver.com:9001/) I get the expected "hello, world" output as well as the console message "Request Received!
GET". From this point on if I click the button to trigger my AJAX call I get a new error.
submitted!
XMLHttpRequest cannot load https://adam.testserver.com:9001/. Origin
https://adam.testserver.com is not allowed by Access-Control-Allow-Origin.
w_worksheet.php:73
complete!
I don't understand why I get this message as both my form and node server reside on the same server. Thanks for taking the time to read, I appreciate any help I can get on this. I've been stuck for a while now!
You've run into the Cross-Origin Resource Sharing (CORS) specification.
Note the OPTIONS in your output. The OPTIONS HTTP Verb is used by the browser to query the web server about the URL, not to GET its contents or POST data to it.
Your server doesn't respond with the correct header data on a CORS request, so your browser assumes it has no rights to access the data, and refuses to GET or POST to the URL.
If you truly want to let any website in the world run that AJAX request, you can do something similar to the following:
function handleOptions(request, response) {
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": request.headers["access-control-request-headers"]
});
response.end();
}
function server(request, response) {
if(request.method == "POST") {
handlePost(request, response);
} else if(request.method == "OPTIONS") {
handleOptions(request, response);
} else {
handleOther(response);
}
}
https.createServer(sslObj, server).listen(9001);
You can fill in the details and whether you should handle GET separately, and so on (handleOther should return an appropriate error code for each request method you don't support).

Resources