Node Js as server http to consume external web service - javascript

I want to install Node Js to consume a external web service in SOAP.
This is the architecture:
|Webshere application| ---HTTP---> |Node Js| ----HTTPS--> ||External Web Service||
This is the script I am doing:
var http = require('http');
var httpntlm = require('httpntlm');
var options = {
url: "https://serverexterno/WebServiceSOAP?wsdl"
}
const server = http.createServer( (req, res) => {
let body = '';
let headers = req.headers
let as400Response ='';
req.setEncoding('ascii');
req.on('data', (chunk) => {
body += chunk;
});
httpntlm.post(options,
function (err, resp) {
console.log (resp);
if(err) {
return console.log(err);
}
console.log( resp.headers);
console.log("resp.body" + resp.body);
body = resp.body;
res.statusCode = 200;
return res.end(resp.body);
});
console.log ('Finish ....');
} catch (er) {
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(8084, function(){
console.log("Server listening on: http://localhost:%s", 8087);
});
However, I don't receive as expected. I receive the message in html with the message "Hello! This is an Axis2 Web Service!". It seems like the webservice is not executing.
Can someone help me why get this error?

Related

Routing for static site causes endless loading in browser when readFile() is in an if statement

I am trying to create routing for a static site however placing readFile() in an if statement causes infinite loading in my browser and content doesn't load.
I'm trying to do this without the use of Express or any similar framework.
Here is my code:
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var server = http.createServer((req, res) => {
let parsedURL = url.parse(req.url, true);
let fPath = parsedURL.path;
if (fPath === "/") {
fPath = "/index.html";
}
file = path.join(__dirname, "/public" + fPath);
if (fPath === "/index.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
} else if (fPath === "/information.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
}
});
server.listen(8000);
If if (fPath === "/index.html") { matches and fs.readFile has an error, then you don't send a response.
The same is true for "/information.html".
And if fPath isn't either of those then you get to the end and you don't send a response.
The endless loading is caused by the browser waiting for a response you never send.
You need to make sure that every path through your if statements calls res.end or another function that sends a response to the browser.

How to get data from custom created function in JS using https node module

How to get data from my function Data() instead of JSON PLACE HOLDER mock API using HTTPS/HTTP node module and how to make an endpoint of this get data HTTP/HTTPS module to utilize response in front end just like Angular?
My mock backen.js file:
const https = require('https');
https.get(Data.data, res => {
let data = [];
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.statusCode);
console.log('Date in Response header:', headerDate);
res.on('data', chunk => {
data.push(chunk);
});
res.on('end', () => {
console.log('Response ended: ');
const users = JSON.parse(Buffer.concat(data).toString());
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
});
}).on('error', err => {
console.log('Error: ', err.message);
});
function Data() {
var data = {};
........
return data;
}
Your time and help will be really appreciated. Thanks :)
Hurray! I got it using the following code and Express in node js. I simply call my custom method that creates data into an express "get" endpoint. When I hit the end point the response will be my custom method result.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/data', (req, res) => {
res.send(
getDashboardData());
});
app.listen(3000, () => {
console.log('server is listening on port 3000');
});
function Data() {
var data = {};
..........
//console.log(JSON.stringify(data));
return JSON.stringify(data);
}

Node js works fine but how do I get it on browser?

I have a table in sql Server and I am trying to display it in web browser and apply datatable(jQuery) to it. Below code works fine as it gives the output in command line. But I'd have to get it on the browser(probably in json format).
I am using 'tedious' for connection as that's what I found in Express.js documentation.
var express = require('express');
var app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
userName: 'clientinfo',
password: 'clientinfo123',
server: 'USW20051234'
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("SELECT * from dbo.Logs", function (err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount+' rows');
}
connection.close();
});
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(JSON.stringify(column.value));
}
});
});
connection.execSql(request);
}
You need to start HTTP server. As you already define APP try this
app.get('/urltest', (req, res) => {
res.send('hello from nodejs');
});
const PORT = 5000;
app.listen(PORT);
console.log('Listening on :' + PORT + '...');
and try http:localhost:5000/urltest on a browser
Thank You everyone for all the suggestions. I think "tedious" was giving me a hard time so I did npm install mssql and that worked like a charm.
Below is the link I referred to.
http://www.tutorialsteacher.com/nodejs/access-sql-server-in-nodejs

Simple Node.js server without Express - piping HTML files to response

I am trying my hand at making a simple Node.js server without Express and this where I actually learn a bit more about the down and dirty of actually server files and data on requests based on paths request and basic HTTP stuff.
I have this straightforward server like so:
var http = require('http');
const PORT = 6969;
var allRoutes = require('./routes/all');
var server = http.createServer(allRoutes);
server.listen(PORT, function () {
console.log("Server listening on: http://localhost:%s", PORT);
});
and then I have one "middleware" function like so that handles all requests:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
}
}
finally {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;
the problem I am having is that my function doesn't seem to pipe the response to the browser. The browser shows no evidence of the data come from index.html, which is a barebones .html HTML5 file.
I stole the example, and am surprised it's not really working. Anyone have an idea? I know for sure that the fs.stat function is not experiencing an error and then it is streaming the index.html file, it just doesn't seem to be streaming to the right place...
For starters:
if (requestUrl.pathname = '/')
should be:
if (requestUrl.pathname === '/')
Your code was assigning, not comparing.
In addition, the .pipe() is asynchronous, but you are calling res.end() BEFORE it gets to do it's job in your finally{} block which closes the response stream and stops your pipe from doing anything. By default .pipe() will close the write stream by itself, so you don't need the res.end() at all when using .pipe().
You can change the code to this:
var url = require('url');
var fs = require('fs');
var appRootPath = require('app-root-path');
var path = require('path');
function handleRequest(req, res) {
var requestUrl = url.parse(req.url);
var fsPath;
if (requestUrl.pathname === '/') {
fsPath = path.resolve(appRootPath + '/view/index.html');
}
else {
fsPath = path.resolve(appRootPath + '/view/' + requestUrl.pathname);
}
fs.stat(fsPath, function (err, stat) {
if (err) {
console.log('error occurred...' + err);
return end(req, res);
}
try {
if (stat.isFile()) {
res.writeHead(200);
fs.createReadStream(fsPath).pipe(res);
}
else {
res.writeHead(500);
end(req.res);
}
}
catch(e) {
end(req, res);
}
});
}
function end(req, res) {
res.end();
}
module.exports = handleRequest;

Node Restify use case to get data gives a "ResourceNotFound"

I just started working with Nodejs.
I am using Restify to get data from: http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'.
My code below gives me an error: {"code":"ResourceNotFound","message":"/ does not exist"}
var restify =require("restify");
var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function (req, res) {
console.log(req.body);
res.send(200,req.body);
});
server.listen(7000, function () {
console.log('listening at 7000');
});
That's because Restify is for creating REST endpoints, not consuming them. You should check out this SO post for help consuming data from an API.
e.g. create test.js with the following:
var http = require('http');
var options = {
host: 'api.geonames.org',
path: '/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
then run node test.js.
I found what I was looking for. You can use restify client to get JSON data:
Here is my solution:
var restify = require("restify");
function getJSONDataFromUrl(){
var query = "?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
var options = {};
options.url = "http://api.geonames.org";
options.type = options.type || "json";
options.path = "/citiesJSON" + query;
options.headers = {Accept: "application/json"};
var client = restify.createClient(options);
client.get(options, function(err, req, res, data) {
if (err) {
console.log(err);
return;
}
client.close();
console.log(JSON.stringify(data));
return JSON.stringify(data);
});
}
getJSONDataFromUrl();

Categories

Resources