Backbone route with push state not working on page refresh - javascript

var Backbone = require('backbone'),
SellerProfileView = require('./views/seller/SellerProfileView');
var Router = Backbone.Router.extend({
routes: {
":user_name" : "sellerProfile"
},
sellerProfile: function (username) {
"use strict";
var sellerProfile = new SellerProfileView({username: username});
}
});
module.exports = Router
var Router = require('./router'),
Backbone = require('backbone'),
$ = require('jquery');
var app = {
init: function () {
"use strict";
Backbone.$ = $;
this.router = new Router();
$(document).ready(function () {
Backbone.history.start({ pushState: true, route: '/' });
});
}
};
module.exports = app;
app.init();
I get the below error if i refresh the page without the hash
Error response
Error code 404.
Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
Please help.

pushState will try to load the ressource.And it seems your server is not loading anything at 'yourwebsiteurl.com/'

Related

express.js router unit testing error

I have a node/express application with a controller and service. While running the unit test for controller via Grunt/Jasmine, the test runs fine but after the coverage summary I get the following error:
error: Error on SAVE state TypeError: Cannot read property 'apply' of undefined
at /node_modules/express/lib/router/index.js:603:14
at next (/node_modules/express/lib/router/index.js:246:14)
at next (/node_modules/express/lib/router/route.js:100:14)
Controller.js
var express = require('express'),
router = express.Router();
module.exports = function(app) {
app.use('/api', router);
router.post('/save', function(req, res, next) {
// Service code is invoked here with the success/error callback
// on success - res.json(response);
// on error - res.status(err.status);
});
}
ControllerSpec.js
var app = require('../mockApp'); // the app.js and the express app is mocked here
var httpMocks = require('node-mocks-http');
var request = require('request');
describe("Controller SAVE Action", function () {
it("With Error", function () {
spyOn(service, "save").andCallFake(function (req, res, headers, callback) {
callback({category: "Error"});
});
var rout = app.getRouter("/state"); // the mocked app.js contains a getRouter function which returns the corresponding router which is simply express.Router()
var request = httpMocks.createRequest({
method: 'POST',
url: '/save',
headers: {"authorization": "success"}
});
var response = httpMocks.createResponse();
rout(request, response);
var data = JSON.parse(response._getData());
expect(data.code).toEqual(400);
});
});
Mocked app.js
var m = {};
var routers = {};
module.exports = {
get: function (name) {
return m[name];
}, set: function (name, obj) {
m[name] = obj;
}, use: function (path, router) {
if (router) {
routers[path] = router;
}
}, getRouter: function (path) {
return routers[path];
}
};
Mocked Express.js
var app = require('./app'); // Mocked app.js
var services = {};
var serviceFiles = glob.sync(rootPath + '/app/services/*.js');
serviceFiles.forEach(function (file) {
var service = require(file)(app);
services[service.serviceName] = service;
});
app.set("services", services);
var controllers = glob.sync(rootPath + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});

Node JS and custom module with express js

I've got this little piece of code:
'use strict';
module.exports = MainCtrl;
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
and on my route file I require like this:
var express = require('express');
var request = require('request');
var main_lib = require('../lib/main_ctrl.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/newroute', function(req,res) {
//var mainCtrl = new main_lib.MainCtrl();
main_lib.getPoi();
res.render('newroute', { title: 'New Route' });
})
module.exports = router;
As you can see is very simple, I'm on my first steps with ExpressJS and NodeJS but I don't know why I've got this error:
TypeError: Object function MainCtrl() { this.defaultUrl = 'http://foo/'; } has no method 'getPoi'
I've look at the definition of the view module on express lib and is the same as:
module.exports = View;
function View(name, options) { .. }
View.prototype.lookup = function lookup(name) { .. }
But I can't understand what I'm doing wrong.
You are getting error for calling function of MainCtrl you need to create object of this class.
Use following code
'use strict';
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
//added function for getting instance
module.exports.getInstance = function () {
return new MainCtrl();
};
While adding controller in router use this:
var main_lib = require('../lib/main_ctrl.js').getInstance();
Now main_lib is object of your controller. So you can call like:
main_lib.getPoi();
If you want to use like View module then manually you have to create object for this. like
'use strict';
module.exports = MainCtrl;
function MainCtrl() {
this.defaultUrl = 'http://foo/';
}
MainCtrl.prototype.getPoi = function getPoi() {
request( 'http://foo/',function(error,response,body) {
console.log( body );
});
};
In route file:
var main_lib = require('../lib/main_ctrl.js');
var main_lib_object = new main_lib();//take a look here
main_lib_object.getPoi(parameter);

Why do I get 'undefined is not a function'?

I'm trying to return a file as a response to a GET request using express.js
I wrote a simple FileManager class to handle file request, however i'm getting the 'undefined is not a function' error ,when I call new FileManager()
Here's, how I try to do this:
//FileManager.js
FileManager = function () {}; //Empty initializer
FileManager.prototype.handleFileRequest = function(req,res){
var fileId = req.params.id
if(fileId){
var path = './uploads/events' + fileId;
res.sendfile(path)
} else {
res.send(404, 'file not found')
}
}
Here's the server:
//server.js
var express = require('express');
var FileManager = require('./FileManager.js').FileManager;
var app = express();
var fileman = new FileManager();
app.get('/:id', function (req, res){
console.log('get id:' + req.params.id);
fileman.handleFileRequest(req,res);
})
app.listen('blabla',3000);
but when I run node server.js , i get the following error:
var fileman = new FileManager();
^
TypeError: undefined is not a function
In FileManager.js ... you need to export the object.
module.exports = {
FileManager : FileManager
}
server.js
var FileManager = require('./FileManager.js').FileManager;
// this has the FileManager object that was created in the FileManager.js

React.js: handleSubmit or onClick not triggered when rendered on the server side

I am having a problem rendering everything on the server side and have a handleSubmit triggered. Here is the source code:
index.js:
module.exports = require('./app/server');
app/server/index.js:
'use strict';
var env = process.env.NODE_ENV || 'development';
var express = require('express');
var http = require('http');
var app = express();
app.set('state', {});
// Inject Config
require('../config/server')[env](app, express);
// Inject component rendering
require('node-jsx').install({extension: '.jsx'});
app.use(require('../../lib/renderReactComponent')(app));
// Start server
var server = http.createServer(app);
return server.listen(app.get('port'), function() {
return console.log('Listening on port ' + app.get('port') + ', Env: ' + app.settings.env);
});
module.exports = app;
lib/renderReactComponent.js:
var ReactApp = require('../app');
var React = require('react');
var path = require('path');
var url = require('url');
module.exports = function(app) {
return function(req, res, next) {
try {
var path = url.parse(req.url).pathname;
res.send(React.renderComponentToStaticMarkup(ReactApp({path: path, state: app.get('state')})));
} catch(err) {
return next(err)
}
}
}
app/index.js:
var ReactApp = require('./components/app');
module.exports = ReactApp;
app/components/app.js:
/**
* #jsx React.DOM
*/
var React = require('react');
var ReactRouter = require('react-router-component');
var App = React.createClass({
propTypes: {state: React.PropTypes.object.isRequired},
getInitialState: function() {
return {items: [], text: ''};
},
handleSubmit: function () {
console.log("handleSubmit triggered!");
var $author = this.refs.author.getDOMNode(),
$text = this.refs.text.getDOMNode(),
author = $author.value.trim(),
text = $text.value.trim();
if(!author || !text) {
return false;
}
if(this.props.onCommentSubmit) {
this.props.onCommentSubmit({ author: author, text: text });
}
$author.value = '';
$text.value = '';
return false;
},
render: function() {
return (
<html>
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" ref="author" placeholder="Your name"/>
<input type="text" ref="text" placeholder="Say Something ..."/>
<input type="submit" value="Post"/>
</form>
</html>
);
}
});
module.exports = App;
This code does not give me an error, but the handleSubmit is not triggered. I think it's because it's not render by the server side. How can I trigger the form event handleSubmit while trying to render the page from the server side ?
The flow works like this:
client requests a page
server does a React.renderComponentToString and returns the html to the client
at this point the server stops doing anything
the page loads on the client, and React.renderComponent is run
React notices the markup with reactids
verifies the checksum
if it's all good, just adds event listeners and waits for something to happen
the user maybe submits the form, invoking your handleSubmit
In handleSubmit, if you'd like to send some data to the server you can do it with the normal AJAX/WebSockets/etc techniques.
Check out superagent for a good http client that works in the browser and node.

How to get a variable defined in index.js from within a controller?

I'm testing forms-angular (http://www.forms-angular.org/).
I define a DataFormHandler variable in my index.js file. And also I need to get this variable in my controllers. How may I get it? This setter doesn't work app.set("formHandler", DataFormHandler).
Here is the code:
index.js
'use strict';
var formsAngular = require('forms-angular'); // require formsAngular
var kraken = require('kraken-js'),
app = require('express')(),
options = {
onconfig: function (config, next) {
//any config setup/overrides here
next(null, config);
}
},
port = process.env.PORT || 8000;
// Here I initialize FormHandler. It requires the app, so I initialize it here, in index.js
// HOW TO GET THIS VAR IN CONTROLLERS?
var DataFormHandler = new (formsAngular)(app);
app.set("fh", DataFormHandler); // THIS DOESN'T WORK. UNDEFINED in controller
app.use(kraken(options));
app.listen(port, function (err) {
console.log('[%s] Listening on http://localhost:%d', app.settings.env, port);
});
The setter app.set("fh", DataFormHandler) doesn't work. When I try to get fh from within a controller it is undefined:
app\controllers\index.js
'use strict';
var UserModel = require('../models/user');
module.exports = function (router) {
var user = new UserModel();
router.get('/', function (req, res) {
var DataFormHandler = req.app.get("fh");
DataFormHandler.addResource('user', UserModel);
console.log("DataFormHandler", DataFormHandler); // undefined
var model = {
hello: "Hello"
}
res.render('index', model);
});
};
How to get a variable in a controller?
I found one solution that works. But not sure that it's the correct one.
Instead of
app.set(key, value)
which doesn't work, I use
app.locals.key = value
that for some reason works.

Categories

Resources