Node HTTP Proxy 403 Post Request Forbidden - proxy

I used Node-http-proxy to proxy my request from port sample.com:80 to port sample.com:8080 with sample below:
var httpProxy = require('http-proxy');
httpProxy.createServer(8080, 'localhost').listen(80);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
When I do: curl with POST to sample.com:80, I get 403 Forbidden response. But when I do curl with GET, 301 permanent redirect. My question is:
Is it possible to make POST and GET behaves the same, which always return 200 status code instead of 403 or 301?
Thanks

var fmt = require('fmt');
var httpProxy = require('http-proxy');
fmt.sep();
console.log();
fmt.title("\033[1;36mPROXY SERVER STARTED\033[0m");
console.log();
fmt.field("\033[1;34mPROXY PORT\033[0m", 80);
fmt.field("\033[1;34mTARGET PORT\033[0m", 8080);
fmt.field("\033[1;34mTARGET ADDRESS\033[0m", '127.0.0.1');
var server = httpProxy.createServer(function(req, res, proxy)
{
proxy.proxyRequest(req, res, { host: '127.0.0.1', port: 8080, buffer: httpProxy.buffer(req) });
var reqBody = '';
req.on('data', function(chunk)
{
reqBody += chunk;
});
req.on('end', function()
{
console.log();
fmt.sep();
console.log();
fmt.title("\033[1;36mREQUEST FROM SHARED CLOUD\033[0m");
console.log();
fmt.dump(req.connection.remoteAddress, "\033[1;35mADDRESS\033[0m");
console.log();
fmt.msg("\033[1;35mHEADERS\033[0m :");
fmt.dump(req.headers);
console.log();
fmt.msg("\033[1;35mBODY\033[0m :");
fmt.dump(reqBody);
console.log();
});
});
server.proxy.on('proxyError', function(err, req, res)
{
fmt.title("\033[1;36mPROXY STATUS\033[0m");
console.log();
fmt.dump('failed to proxy on port ' + 8080, "\033[1;31mERROR\033[0m");
res.end();
});
server.proxy.on('end', function()
{
fmt.title("\033[1;36mPROXY STATUS\033[0m");
console.log();
fmt.dump('request was proxied successfully', "\033[1;33mSTATUS\033[0m");
});
server.listen(80);

Related

Terminal curl: (7) Failed to connect to localhost port 3000: Connection refused

I am using OSX Elcapitan, 10.11.6, when I run
curl localhost:3000
or
curl localhost:3000 -4
or
curl 0.0.0.0:3000
or
curl -x "" "http://127.0.0.1:3000"
It always says:
curl: (7) Failed to connect to 127.0.0.1 port 3000: Connection refused
ruby -v
ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-darwin13.0]
my code:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var url = 'mongodb://localhost:27017/mongo-server';
// Use connect method to connect to the server
MongoClient.connect(url, function(error, db) {
if (error) {
console.error(error.message);
process.exit(1);
}
console.log("Connected to MongoDB successfully.");
collectionDriver = new CollectionDriver(db);
});
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
app.get('/:collection', function(req, res) {
var params = req.params;
collectionDriver.findAll(req.params.collection, function(error, objs) {
if (error) { res.send(400, error); }
else {
if (req.accepts('html')) {
res.render('data',{objects: objs, collection: req.params.collection});
} else {
res.set('Content-Type','application/json');
res.send(200, objs);
}
}
});
});
app.get('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.get(collection, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
res.send(400, {error: 'bad url', url: req.url});
}
});
app.post('/:collection', function(req, res) {
var object = req.body;
var collection = req.params.collection;
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
app.put('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.update(collection, req.body, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
var error = { "message" : "Cannot PUT a whole collection" }
res.send(400, error);
}
});
app.delete('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.delete(collection, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
var error = { "message" : "Cannot DELETE a whole collection" }
res.send(400, error);
}
});
app.use(function (req,res) {
res.render('404', {url:req.url});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
It looks like you didn't start your server, or it's running on a port other than the one you're expecting.
If this is a Rails app, rails c gets it going. If it's some other Rack based program you'll need to launch it another way, like with Pow.

Node.js and Express; POST 404

I can't get my server to call a function from the client using node.js and express. I don't need to pass data, I just need to alert to the server that it should call a function. This is what I have (after following numerous tutorials):
client:
$.ajax({
type: 'POST',
url: 'http://localhost:3001/admin',
sucess: function() {
console.log('sucess');
}
server:
var express = require('express');
var app = express();
var server = require('http').Server(app);
app.set('port', process.env.PORT || 3001);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.post('/admin', function(req, res) {
console.log("admin refresh");
res.send(200);
});
Error:
POST http://localhost:3001/admin 404 (Not Found)
You have your middleware in the wrong order. Express prossess them in order declared. Move your app.post('/admin... line ABOVE your Not Found middleware.

Loading image server node.js

im trying to load image and when I check on the browser if works, it say not found, any ideas of how to fixed.
Thank you
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': body.length
});
res.end(img, 'binary');
};
exports.init = function(cb) {
require('fs').readFile('./image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}

Why isn't the server sending or the client receiving data via socket.io in my express app?

My node app posts an object (consisting of data collected in a form on the client) to Salesforce via their API. On receiving a success or error message, I would like to send it to the client-side, then display it. Socket.io seemed like the tool for this in my simple node/express3 app, but beyond the simple demo I'm not able to get data to pass between my server and my client.
My relevant server side code:
var express = require('express');
var port = 5432;
var app = module.exports = express();
var server = require('http').createServer(app);
var nforce = require('nforce');
var org = nforce.createConnection({
clientId: 'MY_CLIENT_ID',
clientSecret: 'MY_CLIENT_SECRET',
redirectUri: 'http://localhost:5432/oauth/_callback'
});
var io = require('socket.io').listen(server);
// here I authenticate with Salesforce, this works fine
app.post('/salesforce', function(req, res){
var lead = nforce.createSObject('Lead');
// here I construct the lead object, which also works fine
org.insert(lead, oauth, function(err, res) {
if (err === null) {
console.log(res);
leadSuccessMessage(res);
}
else {
console.log(err);
var error = {
errorCode: err.errorCode,
statusCode: err.statusCode,
messageBody: err.messageBody
};
console.log(error);
leadErrorMessage(error);
}
});
}
function leadSuccessMessage(res) {
var resp = res;
console.log('called success message from server');
io.sockets.on('connection', function (socket) {
socket.emit('sfRes', resp);
socket.on('thanks', function (data) {
console.log(data);
});
});
}
function leadErrorMessage(error) {
var err = error;
console.log('called error message from server');
io.sockets.on('connection', function (socket) {
console.log("socket is: " + socket);
socket.emit('sfRes', err);
socket.on('thanks', function (data) {
console.log(data);
});
});
}
And my relevant client side scripts:
<script src="/socket.io/socket.io.js"></script>
<script>
current.page = document.URL;
console.log("current page is: " + current.page);
var socket = io.connect(current.page);
socket.on('sfRes', function (data) {
console.log("client received: " + data);
fst.showLeadStatus(data);
socket.emit('thanks', {message: "received server feedback"});
});
</script>
When I post the form containing valid data using a spicy little AJAX call:
postToSF: function(){
$('#submitLead').on('click', function(e){
e.preventDefault();
var formData = $('#lead_form').serialize();
$.ajax({
type: 'POST',
url: '/salesforce',
data: formData,
success: function(){
fst.log('success!');
},
error: function(xhr, ajaxOptions, thrownError){
console.error(xhr.status); // 0
console.error(thrownError);
}
});
});
}
All I get are tears, and these in the server-side console:
// the result of `console.log(res)`
{ id: '00Qa000001FZfhKEAT', success: true, errors: [] }
// and proof that `leadSuccessMessage()` got called
called success message from server
Instead of calling this function from a client-side object as it's supposed to:
showLeadStatus: function(response){
if (response.success) {
fst.log("showing lead status as: " + response);
$('#leadStatus').addClass('success').removeClass('error').fadeIn().delay(4000).fadeOut();
}
else {
fst.log("showing lead status as: " + response);
$('#leadStatus').text(response.messageBody).addClass('error').removeClass('success').fadeIn().delay('4000').fadeOut();
}
$('#startOver').click();
}
Which works fine if I call it in the console passing it the data the server is supposed to be socketing over:
// this works, gosh darn it
fst.showLeadStatus({ id: '00Qa000001FZfhKEAT', success: true, errors: [] });
The Salesforce post error case doesn't surface anything to the client either. And there are no errors in the client or server console to contend with.
I'm stumped. Please help!
I would do something like this -
var mysocket = null;
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
mysocket = socket;
socket.on('thanks', function (data) {
console.log(data);
});
});
app.post('/salesforce', function(req, res){
....
....
})
function leadSuccessMessage(res) {
var resp = res;
console.log('called success message from server');
if(mysocket)
mysocket.emit('sfRes', resp);
}
function leadErrorMessage(error) {
var err = error;
console.log('called error message from server');
if(mysocket)
mysocket.emit('sfRes', err);
}

https request semantic issue

I'm trying to make an https request from my node server to my main php server but it looks like the request isn't going through. I'm pretty sure there is an issue with the hostname line as I have read people having random issues with it but it could be something else. The php server is secured with ssl and is an amazon ec2.
exports.authenticate = function(request, callback) {
var https = require('https');
var options = {
hostname: 'https://mysite.com',
port: 443,
path: '/ajaxim/auth.php',
method: 'GET',
cookie: exports.cookie + '=' + request.sessionID
};
var req = https.request(options)
req.end();
req.on('response', function (response) {
var data = '';
response.setEncoding('utf8');
response.on('data', function(chunk) {
data += chunk;
});
//console.log (request.sessionID);
response.on('end', function() {
try {
callback(JSON.parse(data));
} catch(e) {
callback();
}
});
});
};
Any suggestions will be insanely helpful. I'm just trying to get hint of the right direction.

Resources