Can feathers co exist with routs managed out side of feathers - feathersjs

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.

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");

To forward a JSON file to other Address with Express js

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

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

ExpressJS POST cannot log body

After a lot of fiddling with upgrading versions and the different middleware/ways of using a body parser, I am still stuck.
I have an Iphone app which POSTs 2 things (2 separate things). First is an image, which works.
Second is a json object which i try to put into mongodb.
No matter what i do, i can't seem to log the contents of the request.
var express = require('express');
var logger = require('morgan');
var fs = require('fs');
var json = require('express-json');
var path = require('path');
var errorHandler = require('errorhandler');
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
FileDriver = require('./fileDriver').FileDriver;
...
app.use(json());
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
...
app.post('/:collection', function(req, res) {
console.warn(req.body.poi.toString());
var object = req.body;
var collection = req.params.collection;
console.warn("Post: " + req.toString());
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
I've tried logging (log, warn) req.body, req, etc. to no avail.
i'm using express-json and NOT url encoding, don't think need it.
morgan ouputs the following when i post
POST /pois 200 15.983 ms - 63
and nothing else!
It apparently cannot do it, as stated in this closed issue https://github.com/expressjs/morgan/issues/16
morgan is not intended for this kind of work. Try and use Winston instead, or simply console.log
This does it for me:
const express = require('express')
const app = express()
app.use(express.json())
var morgan = require('morgan')
morgan.token('response-body', (req, res) => {return JSON.stringify(req.body)}); // define 'response-body' token using JSON.stringify
app.use(morgan(':method :url :response-time :response-body')) //include newly defined ':response-body' token
app.post(/....)