I'm trying to use nodejs as a layer between my public website and a server on the inside of our network.
I'm using express.js to create a simple REST api. The API endpoint should trigger a request call to a webservice, and return the result.
But the request call inside my .get() function doesn't do anything.
I want to return the result from the nested call to be returned.
Code:
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is workiung on IISNode')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
res.send('Customer ID: ' + req.params.customerId + ' Invoice ID: '+ req.params.invoiceId)
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request('http://www.google.com', function (error, response, body) {
res.send(body);
})
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Any suggestions?
You can write in this way
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is working')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request(url, function (error, response, body) {
var data={
body:body,
customerID:req.params.customerId,
invoiceID:req.params.invoiceId
};
res.send(data);
});
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Please find the snippet I am using. Hope this helps for you as well.
var body="";
function callyourservice(customerId,invoiceId,callback) {
var options = {
uri : url + 'costumer=:customerId&invoice=:invoiceId',
method : 'GET'
}
request(options, function (error, response, body) {
console.log(response);
if (!error && response.statusCode == 200) {
res = body;
}
else {
res = 'Not Found';
}
callback(res);
});
}
callyourservice("customerId value","invoiceId value", function(resp){
body=JSON.stringify(resp);;
});
You can write callyourservice inside a get method from client like
app.get('/'){
}
You can try doing it the node way using pipe
var http = require('http');
http.createServer(function(request, response) {
var proxy = http.createClient(9000, 'localhost')
var proxyRequest = proxy.request(request.method, request.url, request.headers);
proxyRequest.on('response', function (proxyResponse) {
proxyResponse.pipe(response);
});
request.pipe(proxyRequest);
}).listen(8080);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
You can find the reference here
Related
I Have a Node app, I have three files and am trying to structure my node in a MVC pattern.
I want a way to put all my requires and variables in my server.js all the routes in my routes.js and my functions in my controller.js.
My router is fine and works.
How do I include the functions from controller in my server file
I have:
server.js
var configure = require('./router');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
configure(router);
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// // START THE SERVER
// // ==============================================
app.listen(port);
console.log('Server has started!! ' + port);
// apply the routes to our application
app.use('/', router);
router.js`
module.exports = function (router) {
// route middleware that will happen on every request
router.use(function (req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
// home page route (http://localhost:8080)
router.get('/', function (req, res) {
res.send('im the home page!');
});
router.get('/login', function (req, res) {
res.send('this is the login form');
})
// process the form (POST http://localhost:8080/login)
.post('/login', function (req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
};
controller.js
var password = 'gf.09';
var userkey = 'dfgg';
var emailAdmin = 'rt.r#rt.co.uk';
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
var secondFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
function thirdFunction(result) {
return new Promise (function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
// sequence of functions
Promise.all([firstFunction(), secondFunction()])
.then(thirdFunction);
What I have tried
var routers = require('./router');
var controller = require('./test');
// var controller = require('./test.js','./router' );
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
var router = express.Router();
routers(router);
controller(Promise);
and
module.exports = function (Promise) {
all functions
}
Problem is some of the variables are not available to controller.js so i get errors such as :
app.post('/back-end/controller', function (req, res) {
^
This is dead simple use same logic as you applied in your router.js.
Use something like below in controller.js:
exports.function_name = function(params, ...){
. . .
}
Then access these function by importing the controller.js
var controller = require('./controller.js');
controller.function_name(param..) # execute with required params and callback
If you want to return an object then you can do module.exports
module.exports = Promise.all([firstFunction(), secondFunction()]) .then(thirdFunction);
The controller object contain a promise now so
var controller = require('./controller.js');
controller object directly can be used as a promise no need to call a function now.
A better alternative is to export all the functions from controller.js and then in app.js you can use them with promise.
Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);
I can't figure out how to write on a JSON file.
I'm working on a Single Application Page, using mostly AngularJS and Node.js
This is my code:
--index.html--
<script type="text/ng-template" id="pages/Animazione.html">
...
<td><input id="clickMe" type="button" value="clickme" ng-click="doPost()" /></td>
--app.js--
var App = angular.module('myMovie', ['ngRoute']);
...
.when('/Animazione', {
templateUrl : 'pages/Animazione.html',
controller : 'AnimazioneController'}
)
...
App.controller('AnimazioneController', ['$scope','$http', function($scope, $http) {
$http.get('Animazione.json').success(function(response)
{
$scope.myData=response;
})
.error(function()
{
alert("Si รจ verificato un errore!");
});
$scope.doPost = function()
{
writeOutputFile({test: 1});
};
}]);
--index.js-- (Server)
function writeOutputFile(data, success, fail) {
var fs = require('fs');
fs.writeFile('auth.json', JSON.stringify(data), function(error) {
if(error) {
console.log('[write output]: ' + err);
if (fail)
fail(error);
} else {
console.log('[write output]: success');
if (success)
success();
}
});
}
Is there any call or any function that I'm doing wrong?
As far as I know, you can't call a function directly which in the server via client.
To do this, define and end point in the server and from client make a call to that end point. Inside the handler for that end point in server call your function to write to file.
Eg: In server define /writefile endpoint like below (where express is used in server side) Add below contents to index.js
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http');
var cors = require('cors');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());
app.post('/writefile', function(req, res) {
var fileData = req.body.fileContent;
fs.writeFile('message.txt', fileData , function(err) {
if (err) {
res.status(500).jsonp({ error: 'Failed to write file' });
}
res.send("File write success");
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Now your server is running in 3000 port.
In client:
$http({
method: 'POST',
url: 'http://localhost:3000/writefile', // Assuming your running your node server in local
data: { "fileContent": {"test": 1} } // Content which needs to be written to the file 'message.txt'
}).then(function(){
// Success
},
function(error) {
//error handler
console.error("Error occured::",error);
});
I'm attempting to send data from one machine to another in node.js.
I seem to be having some difficulty getting the parser to function correctly.
Here is my client and server code
Client.JS
var request = require('request');
request.post(
'http://192.168.1.225:3002',
{ form: { key: 'notyourmother' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
Server.JS
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());
app.post('/', function (req, res) {
res.send('POST request to the homepage');
console.log(req.body);
});
var server = app.listen(3002, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
When I run both snippets, the console outputs "{}".
What may I be doing incorrect?
Thank you!
You're using the wrong body parser on the server side. request is sending a application/x-www-form-urlencoded request payload with your current client code. So simply swap out bodyParser.json() with something like bodyParser.urlencoded({ extended: false }).
I have built few rest API on server and calling them from other domain the Get request is working fine but I am facing an issue in calling the POST request.
I am unable to receive data on server send by the clients.
Server Code:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//var fn = require('fn')
var app = express();
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.send(200);
}
else {
next();
}
};
// all environments
app.set('port', process.env.PORT || 3000);
app.use(allowCrossDomain);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.post('/user', user.saveUser);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
exports.saveUser = function(req, res) {
var key = req.body.key; //fb,twitter,web
var userData = req.body.userData;
var result = checkUser(userData,key);
}
Clients code where the request is made :
var data = { key: 'web', userData: userData }
$.ajax({
method: "POST",
//contentType: 'application/json',
url: "www.acbd.com/user",
//url:"http://prayable-21641.onmodulus.net/user",
data: data,
crossDomain: true,
dataType: "json"
}).success(function (data, textstatus) {
// this callback will be called asynchronously
// when the response is available
console.log(data)
console.log(textstatus)
}).error(function (data, textstatus) {
console.log(data)
console.log(textstatus)
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I am unable to get key or userData on server, it say they are not defined:
TypeError: Cannot read property 'key' of undefined
You forgot to require and use the body-parser middleware module.
And also, why is content-type commented out? You need it
Server code should look like this:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//var fn = require('fn')
//requiring body-parser
var bodyParser = require('body-parser');
var app = express();
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.send(200);
}
else {
next();
}
};
// all environments
app.set('port', process.env.PORT || 3000);
app.use(allowCrossDomain);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// using body-parser
app.use(bodyParser());
app.post('/user', user.saveUser);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
also, don't forget to npm install it:
npm install body-parser
//REquire the body parser, make sure you install it using
npm install body-parser
var bodyParser = require('body-parser');
and then use it
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
Hope that helps
I've set up a simple node server and test program from the Node: up and running book. It seems to be working fine when I trace it through with debug but I'm curious why console.log doesn't output anything to the terminal.
Server, app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 8000)
app.use(express.urlencoded());
app.use(express.json());
app.use(express.logger('dev'));
var tweets = [];
app.get('/', function (req, res) {
res.send('Welcome to Node Twitter');
});
app.post('/send', function(req, res) {
if (req.body && req.body.tweet) {
tweets.push(req.body.tweet);
res.send({status:"ok", message:"Tweet received"});
} else {
// no tweet ?
res.send({status:"nok", message:"No tweet received"});
}
});
app.get('tweets', function (req, res) {
res.send(tweets);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Test script, test.js
var http = require('http');
assert = require('assert');
var opts = {
host: 'localhost',
port: 8000,
path: '/send',
method: 'POST',
headers: {'content-type':'application/x-www-form-urlencoded'}
}
var req = http.request(opts, function(res) {
res.setEncoding('utf8');
console.log("Sending test");
var data = "";
res.on('data', function(d) {
data += d;
})
res.on('end', function() {
assert.strictEqual(data, '{"status":"ok", "message":"Tweet received"}');
console.log("test");
})
})
req.write('tweet=test')
req.end
Would love some advice.
The event end never gets fired because you don't call the function req.end. You maintains the http request/connection open. You never finish it.
Try instead:
req.end();
Think about the difference between:
console.log('HI');
console.log;