Issue passing data to child routes in Node.js - javascript

Im new to Node.js and keep getting the Error: Route.get() requires callback functions but got a [object Undefined] error
and Ive checked out the following question and either dont understand or im still doing something wrong
Express routes: .get() requires callback functions but got a [object Object]
.get() requires callback functions but got a [object Undefined]
Error: Route.get() requires callback functions but got a [object Undefined]
Node Route.get() requires callback function but got a [object undefined]
my file structure is
server.js
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
ROOT: server.js
var geolocation = require('./routes/api/geolocation')(app);
app.get('/geolocation/', geolocation.delegate);
then I pass my data to routes/api/geolocations.js by using
geolocation.delegate(unparsedData);
from there I parse the data and send it down it's appropriate child routes.
PARENT: geolocations.js in my routes/api/geolocations.js
var destination = require('./geolocations/destination');
var region = require('./geolocations/region');
module.exports = function(app) {
return {
app.get('./geolocation/region', region.delegate);
app.get('./geolocation/destination', destination.delegate);
delegate: function(unparsedData, req, res) {
var data =[setup package for child states using unparsedData]
//HERE Id like to pass the new `data` to region or destination using the following
region.delegate(data);
//OR
destination.delegate(data);
CHILDREN: region.js / destination.js in routes/api/geolocations/regions.js or routes/api/geolocations/destination.js
module.exports = function(app) {
return {
delegate: function(data, req, res) {
...do stuff
}
}
}
UPDATE: I guess I dont know where to set up my routes, in server.js or if i can in geoloaction.js, does it matter, do need to do something like this in server.js?
var regions = require('./routes/api/geolocation/regions')([pass stuff here]);
geolocation.get('./routes/api/geolocation/regions', regions.delegate);

You should use express.js easy setup and run.
Simply download IntelliJ IDEA, find free version, then install. Then run the application and goto File->Setting->Plugin and search for NodeJS then install. Followed to this you need to Enable it. To do this goto File->Setting->Language & Frameworks->open arrow-> JavaScriptopen arrow->Libraries->Enable Node.js Core.
File Structure
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
You can have a look at the below code that might help you get started.
//------------------------------------------------------------------------
var express = require('express');
var router = express.Router();
var regions = require('../api/geolocations/regions');
var destination = require('../api/geolocations/destination');
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* geolocation.js */
router.get('/', function(req, res, next) {
var region_ext = regions.to_export;
var destin_ext = destination.to_export;
res.render('index', {
title: 'Geolocation',
region: region_ext,
destination:destin_ext
});
});
module.exports = router;
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* region.js */
var to_export = function () {
return 'this is from regions';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* destination.js */
var to_export = function () {
return 'this is from destination';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//In app.js, just change
var routes = require('./routes/api/geolocations');
//------------------------------------------------------------------------

jfriend00 is right, You got a little mess there. Maybe you should consider make use of next(), since if you use it the other middlewares will have a chance of manipulating the request.

Related

Cant understand this Express JS source snippet

I was trying to understand Express JS source and this is the main module where express is exported
module.exports = createApplication;
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
I am confused about this piece of code
var app = function(req, res, next) {
app.handle(req, res, next);
};
The variable app is assigned and used inside the function at the same time. How can this work? There is no definition of an app anywhere else. Find the real source here.
The function is created and assigned to the app variable. That's a normal function expression assignment.
Then, the two mixin() lines add methods to the app function. So, after calling those functions, it has things like app.handle() and app.init().
Then, two more properties app.request and app.response are added.
Then, app.init() is called.
Then, sometime later the app function is called (when an http request arrives) and when it is called, it calls app.handle() which is just calling a function that is a property of itself. That's all legit. It would be similar to calling this.handle() in a more traditional object.
Here's a little demo of the part that seems to have you most confused:
var test = function() {
test.doSomething();
}
test.doSomething = function() {
console.log("doSomething");
}
test(); // causes test.doSomething() to get called

Express & React - How can i transfer my var from one .js to another

I'm working on project that use Node Express and React.
Here's my project's dir
I would like to send a var which is an array of JSon from my app.js to index.js.
How should i do?
Ask questions if you need more informations.
export a function that takes the array as an argument.
index.js
module.exports = function(array) {
console.log(array);
}
and call it from app.js
var index = require('./index');
index([]);
You should not directly import variables from server.
Instead in your App, retrieve that data via api call.
Anyway, when you need to use data from another file, use import and export statement
For example
bookstore.js
export default const = [
{isbn: '1234-4567-6544', name: 'Learn React'}
]
app.js
import books from './bookstore';
// use books here
I believe you're asking more about how to send data between client and server.
With express, you can create a route, that sends the JSON var via a get request made by your react client.
Heres a bit of example code:
//Serverside (EXPRESS)
var app = express();
var myJson = { "foo": "bar" };
app.get('/myjson', function(req, res) {
res.send(JSON.stringify(myJson));
});
//CLIENTSIDE (REACT)
...
import axios from 'axios';
...
...
myFunction() {
var serverAddress = "<insertserveraddresshere>"
axios.get(serverAddress+`/myjson`)
.then(res => {
console.log(res); //json should be here
});
}
...
Thx you three for your time.
I think matt is closest to what i want to do.
I tried this:
//Serverside (EXPRESS)
...
app.get('/jsonSansAnonymous', function (req,res){
res.send(JSON.stringify(jsonSansAnonymous));
});
...
//CLIENTSIDE (REACT)
...
var serverAddress = "http://localhost:9000";
axios.get(serverAddress + `/jsonSansAnonymous`)
.then(res => {
alert(res);
});
...
Here's what i get
Did i do something wrong? maybe my var serverAdress wasn't what you were talking about.
My var jsonSansAnonymous isn't just an Json, but an Array of Json.
Thx again for your help.

MEAN stack/angularjs post request failure

Im struggeling to get the server to accept my post request, cause i would like to post some data on /api/kill .
For some reason it wont work. how can i make it work?
I downloaded the latest release for Mean stack by this link: https://github.com/dickeyxxx/mean-sample
i tried to edit the article module to start with.
var promise = $http.put('/api/kill', null);
response:
angular.js:11756 PUT SITE:3000/server-error 404 (Not Found)
attempt number two:
var promise = $http.post('/api/kill', null);
returns:
angular.js:11756 POST SITE:3000/api/kill 404 (Not Found)
( only if the route is:
app.route('/api/kill').all(articlesPolicy.isAllowed)
.get(articles.list)
.put(articles.killuserbyid)
so, if route is :
app.route('/api/kill').all(articlesPolicy.isAllowed)
.get(articles.list)
.post(articles.killuserbyid)
it would return the orginal:
angular.js:11756 PUT SITE:3000/server-error 404 (Not Found)
MY codes:
in my article.server.routes.js i do have:
'use strict';
/**
* Module dependencies
*/
var articlesPolicy = require('../policies/articles.server.policy'),
articles = require('../controllers/articles.server.controller');
module.exports = function (app) {
// Articles collection routes
app.route('/api/kill').all(articlesPolicy.isAllowed)
.get(articles.list)
.put(articles.killuserbyid)
.delete(articles.delete);
// Single article routes
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
};
my invokeRolesPolicies in articles.server.policy:
exports.invokeRolesPolicies = function () {
acl.allow([{
roles: ['admin'],
allows: [{
resources: '/api/kill',
permissions: '*'
}]
}, {
roles: ['user'],
allows: [{
resources: '/api/kill',
permissions: '*'
}]
}, {
roles: ['guest'],
allows: [{
resources: '/api/kill',
permissions: '*'
}]
}]);
};
my ArticlesListController function in list-articles.client.controller:
ArticlesListController.$inject = ['ArticlesService','$scope'];
function ArticlesListController(ArticlesService,$scope) {
var vm = this;
vm.testing = function() {
ArticlesService.test();
}
}
and, finally my articleservice function (articles.client.service)
ArticlesService.$inject = ['$resource','$http'];
function ArticlesService($resource,$http) {
var o = [];
o.test = function() {
console.log("tester..");
var promise = $http.put('/api/kill', null);
promise.then(function(payload) {
console.log(payload.data);
});
}
return o;
}
If I am understanding your question/issue correctly, you are receiving a 404 error, when issuing a POST request to /api/kill in article.server.routes.js
Correct me if I'm wrong, but your current route in your code is:
app.route('/api/kill').all(articlesPolicy.isAllowed)
.get(articles.list)
.put(articles.killuserbyid)
.delete(articles.delete);
As it stands, there are only route handlers for GET PUT and DELETE requests. There are no route handlers for POST requests, so your server is issuing a 404 error since it cannot find a route handler to respond to POST requests to /api/kill.
Try modifying your route to something like the below and see if you get a response
app.route('/api/kill').all(articlesPolicy.isAllowed)
.get(articles.list)
.post(...) // replace ... with appropriate route handling function
.put(articles.killuserbyid)
.delete(articles.delete);

Backbone Marionette middleware only runs on first route load

I am trying to add some middleware to Marionette's extended version of Backbone's router. Here's my code.
AppName.Router = Backbone.Marionette.AppRouter.extend({
appRoutes:{
// routes
},
route: function(route, name, callback) {
var router = this;
if (!callback) {
callback = this[name];
}
var middleware = function() {
console.log('in middleware');
callback.apply(router, arguments);
};
return Backbone.Router.prototype.route.call(this, route, name, middleware);
}
});
What I think should be happening is whenever I load a route, the console prints 'in middleware'.
What is happening is whenever I load the first route and only the first route, the console prints 'in middleware'.
I researched by using the top solution on this question and these are the results that I get.
Edit: I have also tried 'execute' as specified in the documentation and have had the same results.

Undefined Value For Response Body in Node.js in an Exports Function.

I have a controller accessed from a route through a
router.post('/human',human.create);
human is imported through its controller file which contains the following :
var config = require(__dirname + '/../config/config'),
logger = require(__dirname + '/../lib/logger'),
util = require(__dirname + '/../helpers/util');
exports.create = function(request, response, next){
response.send({
id: "human_103tsG2eZvKYlo2CW5yEDyUe",
firstName: "Patricia",
middleName: null,
lastName: "Cesar",
sex: "Female",
birthdate: null
});
};
Inside this create function, I can do
console.log(request);
And a humongous JSON object will apear in the terminal, including the attribute I need : body.
However, when I do, console.log(request.body), it goes undefined.
Am I missing a particular functionality of Node or Express that needs to be coded out?
I guess you are using the express 4.x which decoupled lots of middleware packages, as #shredmill metioned, you should use
bodyParser = require ('body-parser')
...
app.use(bodyParser.json()); //i found this works for me comparing to use bodyParser()
req.body is not pre-parsed for you automatically. You should explicitly use the connect.json() middleware for this:
var connect = require('connect');
router.post('/human', connect.json(), human.create);

Categories

Resources