To forward a JSON file to other Address with Express js - json

Just starting to learn express. Would wish to forward a json file to another location for processing/ingestion that i recieved from a request from webhook using POST url endpoint.
I am planning to pass this json file to a cpp program
I have the following code
var request = require('request'),,
express = require('express'),
path = require('path');
http = require('http');
const port = 5000;
var app = express();
// for json parser
app.use(express.json());
app.post('/gethub', function(req, res) {
console.log("Got response: " + res.statusCode);
console.log("Got header: " + res.getHeaderNames());
console.log("Got status Message: " + res.statusMessage );
var data = req.body;
var name = data.pusher.name;
var node_id = data.sender.node_id;
res.status(200).send(res.json( { name : name,
Nodeid : node_id });
});
var server = app.listen(app.get('port'), function() {
var host = server.address().address
var portid = server.address().port
console.log('App listening at http://%s:%s', host, portid)
console.log("App listening on port " + app.get('port'));
});
THanks for your help

Think of Express as a framework that behaves as a web server. What you really are doing is writing an API listening in the port 5000 in your case. The function seems ok so it will be accesible while making a HTTP request using the POST method.
Express docs about routing

Related

trouble in sending data through ajax to express server

I'm new to backend and I was having some trouble in sending data through vanilla ajax to my express server.
please tell me where am I going wrong
my ajax request:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
my express server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
I'm receiving an empty object as the output in my console
There are few things to change.
The client is a POST request but in server side, it is a GET app.get(). Therefore, nothing displayed after request.
Also, Content-type needs to be set to inform server how it is going to parse the message. e.g. JSON/form-data
I assume you want to use POST, below is the change:
Backend:
Change method from app.get to app.post
Get the data from body instead of query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
Frontend:
Set content-type
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

Can feathers co exist with routs managed out side of feathers

We have a large app which uses express for rest and primus for socket routes. It would be very hard to convert all to feathers at once. I am thinking of phased approach where I could take some routes and convert them to services and of cause any new routes will follow the service pattern. I will slowly migrate the rest of the app.
The client is using primus and angularjs $http for now to communicate with nodejs.
our current set up looks like
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const csrf = require('csurf');
var Primus = require('primus');
var SocketService = require('./../services/socket-service'); ////this handles existing socket routes from primus client using spark.write
var routesUtils = require('../utilities/routes-utility');
var _ = require('lodash');
module.exports = function(isClusteredDeploy) {
var app = express();
var server = http.createServer(app);
var primus = new Primus(server, {transformer: 'uws'});
var socketService = SocketService(primus);
var commonSocketRoute, commonRoute;
//primus.library();
//primus.save(__dirname + '/primus-client.js');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json({
strict: false,
limit: '1mb'
}));
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') {
return next(err);
}
res.status(403);
res.send();
});
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
server.listen(config.get(constants.CONFIG_App_Port), function() {
log.info('App server ==> %s is listening on port %d', config.get('rest_host_config.' + config.get('app_key') + '.host'),
config.get(constants.CONFIG_App_Port));
});
//dynamically loading rest routes and socket routes from the file system
var files = routesUtils.readRoutes(true);
files.forEach(function(file) {
if (_.includes(file, 'socket')) {
commonSocketRoute = require('./../../' + file);
commonSocketRoute(socketService);
} else {
commonRoute = require('./../../' + file);
commonRoute(app);
}
});
};
I'd like to add feathers in this and then slowly start converting. Is this possible?
Yes, with the standard #feathersjs/express framework integration your Feathers application will also be a fully Express compatible application which additionally allows to register services.
In your case you would replace var app = express(); with:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up REST services (optional)
app.configure(express.rest());
And everything should continue to work as normal. The next step would be to replace the custom Primus code with the #feathersjs/primus framework adapter:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const primus = require('#feathersjs/primus');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up Primus with SockJS
app.configure(primus({ transformer: 'ws' }));
Now you can also replace the http.createServer setup with a more simple
const server = app.listen(config.get(constants.CONFIG_App_Port))
Since Feathers will handle all the Express and Primus initialization. The Primus instance will be available as app.primus.

how to render Rest api JSON data to the HTML page using Node.js without using jquery

I am trying to consume a RESTful API for JSON data and trying to display it on the HTML page.
Here is the code for parsing API into JSON data.
var https = require('https');
var schema;
var optionsget = {
host : 'host name', // here only the domain name
port : 443,
path : 'your url', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
var chunks = [];
res.on('data', function(data) {
chunks.push(data);
}).on('end', function() {
var data = Buffer.concat(chunks);
schema = JSON.parse(data);
console.log(schema);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
var express = require('express');
var app = express();
app.get('/getData', function (request, response) {
//console.log( data );
response.end(schema);
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I am able to get the data in the JSON format but how do I display it in the HTML page? I am trying to do it using node js as I don't want to use jquery for that. Any help would be greatly appreciated. Thanks
your json can render through ejs
npm i ejs
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname+'/public'));
app.get('/view/getData', function (request, response) {
//here view/getData is getData.ejs file in the view folder
response.render(__dirname+'/public/view/getData'',{schema: schema});
//schema is the object wich reference through the view in ejs template
});
your view file here getData.ejs
//store your getData in view/getData.ejs
<h> <%= schema[0]%> </h>//your json data here
basic ejs reference here
res.render brief explanation here

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

Displaying streaming twitter on webpage with socket.io/node.js

I'm trying to build a Twitter streaming web application using node.js socket.io and twit.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
io.sockets.on('connection', function (socket) {
console.log('Connected');
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
T.stream('statuses/filter', { track: watchList },function (stream) {
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
console.log(tweet.text);
});
});
});
Here's my client side
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('tweet', function(tweet) {
$(
'<div class="tweet">' + tweet.text + '</div>');
});
});
</script>
</div>
When I run node app.js and try to connect to localhost:8080 I just get a blank page, even if everything ( soket.io, jquery, ... ) seems to have loaded correctly.
Here's a sample of the server output :
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized pwH0dbx4WvBhzSQXihpu
debug - setting request GET /socket.io/1/websocket/pwH0dbx4WvBhzSQXihpu
debug - set heartbeat interval for client pwH0dbx4WvBhzSQXihpu
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"stream","args":["RT #mintycreative: Great to chat today RT #SharonHolistic: Treatments available tomorrow http://t.co/5Poq3KU08u Book yours now #WestMidsHou…"]}
debug - websocket writing 5:::{"name":"stream","args":["RT #laurenpeikoff: #BREAKING #ScottsdalePD confirms - police are investigating Michael Beasley for alleged sexual assault. #12News #azcentr…"]}
Hope you can help me to correct my mistakes.
Problem solved
Here's the code without any mistakes : (server side)
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
io.sockets.on('connection', function (socket) {
console.log('Connected');
var stream = T.stream('statuses/filter', { track: watchList })
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
});
});
});
(client-side)
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('stream', function(tweet){
$('#tweetd').append(tweet+'<br>');
});
</script>
<div id="tweetd"></div>
</div>
The first issue is that you are constructing a new twitter listener each time a socket connection is opened. You should move that outside of the connection event. This is likely not ideal. I'm not sure how the twitter module is handling that internally but it likely actually is creating a new connection to their API each time a websocket connects.
On the client side you jQuery could bit a bit different. If you just wanted to add a tweet to the page each time a tweet occurs, append a new tweet to the body element with $('body').append()
See this gist for reference.