nodejs ExpressJs BackboneJs pushstate - node.js

I've got problemas with Backbone.history.start({pushState: true}); when is actived
I use the backbone router 'example/:id':'test' and the browser returns me an error
GET myhost:1337/example/js/views/test.js 404 (Not Found)
I want to rotate with Backbone for example myhost:1337/example/test without the necessity to request nodejs.
si, I dunno why,
Could be my server Nodejs?
Or Could be my code that it's not well written?
Thanks in advance
MY server code is
//var http = require('http');
var path = require('path'),
express = require('express'),
routes = require('./routes/index'),
http = require('http'),
app = require('express')();
app.configure(function(){
//app.set('view options',{layout: false });
app.set('port', process.env.PORT || 1337);
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the ned middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
});
app.get('*',function(req,res){
res.setHeader('content-type', 'text/javascript');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.redirect('http://localhost:1337#'+req.url);
});
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});

This is something with your server. I'm willing to bet you didn't hold the shift key down when you typed out your route, so you have something like this in your server
app.get('example?:id':'test', function() {});
When you should have:
app.get('example/:id':'test', function() {});
This block:
app.post('/addPlace?:?',routes.addPlace);
app.get('/searchPlace?:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById?:id',routes.showPlaceById)
app.post('/deletePlace?:?',routes.deletePlace);
See the ?'s everywhere? This should really be:
app.post('/addPlace',routes.addPlace);
app.get('/searchPlace/:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById/:id',routes.showPlaceById)
app.post('/deletePlace',routes.deletePlace);
If you change that, /showPlaceById/:id will return what you expect.

Related

Run NestJS application using app.js (express)

I have a NestJS application that starts fine with:
npm start (npm run start:prod)
or
node dist/main
However, I want to use app.js and can't figure out how to configure the app.js file to accomplish this.
app.js file
var serverType = 'AM-API-MDD';
var express = require('express');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3030;
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
next();
});
app.use(express.static(__dirname + '/dist/'));
//body parse
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }))
// parse application/json
app.use(bodyParser.json({limit: '50mb', extended: true}))
app.all('/*', function(req, res, next) {
res.sendFile('dist/main.js', { root: __dirname });
});
// Handle 404
app.use(function(req, res) {
//res.send(‘404: Page not Found’, 404);
res.status(404).send({status:404, message: '404 Not Found', type:'client'});
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500).send({status:500, message: 'internal error', type:'internal'});
});
//listen
var httpServer = http.createServer(app);
httpServer.listen(port,() => console.log(serverType +' server running on port: '+ port));
trying to get app.js is the wrong approach.
node dist/main.js runs the application - so the startup script is the main.js file.
node-windows can reference the main.js file, rather than the app.js file.
Thanks to Jay McDoniel for pushing me in the right direction.

Why content of middleware is running four times on single request from browser

Why does console.log('First Log') run 4 times per request?
//app.js
const express = require('express');
var app = express();
app.use((req, res, next) => {
console.log('First Log'); // problem is here
next();
});
app.use((req, res, next) => {
res.send('first response from express');
});
module.exports = app;
//server.js
const http = require('http');
const app = require('./backend/app');
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Output:
First Log
First Log
First Log
First Log
Middleware can be generic to all paths, or triggered only on specific path(s) your server handles. Below is an example of middleware declaration.
var app = express();
app.use(function () {}) //added to all paths or globally
app.get('/someroute', function() {}) //added to a specific path
Ref:
https://medium.com/#agoiabeladeyemi/a-simple-explanation-of-express-middleware-c68ea839f498
Answer mentioned in the comment by #AikonMogwai is also correct:
The middleware works one time for each url(of the same route path): index.html, favicon.ico, *.css, etc.
Change console.log to console.log(req.url) to see that.

Reaching Node.js server externally from Google Compute Engine

I have a simple server on node.js running on GCE but I cannot reach the server externally. I'm not sure what is wrong as there is not much indications. Here is my code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
app.use(function(req, res, next){
console.log('Request Type:', req.method);
console.log('Request query:', req.query);
next();
});
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
const PORT = 8080;
app.get("/getVideo", function (req, res){
fs.readFile('./index.html', function (err, html){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(html);
res.end();
})
});
app.listen(PORT, '0.0.0.0');
I can ping the external ip exposed by GCE, but i just cannot reach it. Is there any other setup i need this to work? Or is the code incorrect?
I solved it from Hiren's comment. To go further, I've actually did what he said before, but the thing that did it was the tags. If you set something random, it would not work as it needs to match some other tags. But I left it empty just to test, and it applied it to all instances, and worked.

express server unresponsive after 5 POST's

I am using express to serve a single page webapp, and as a REST endpoint for said app. Everything works fine for the static page serving, but after 5 posts the server becomes unresponsive. I have seen a lot of other posts with this problem but they all say to just make sure to call res.send() or res.end() which i do in every call somewhere, regardless of how the logic branches. The app.js code is below.
/**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
var auth = require("./controllers/authentication.js");
http.globalAgent.maxSockets = 100;
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.get('/public/*', function(req, res) {
res.sendfile('.'+req.url);
});
app.post('/auth/login', function(req, res, next) {
auth.login(req, res, next);
});
app.post('/auth/logout', function(req, res, next) {
auth.logout(req, res, next);
});
app.post('/auth/verify', function(req, res, next) {
auth.verify(req, res, next, function(req, res, next) {
res.conentType = 'json';
res.send(200, "authorized");
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and here is the command line output that i get (i tried issuing other requests after, but the server would not process them). I assume that I am somehow not terminating the connection properly, but cant figure out how.
problem was related to not closing mysql connection pool

How can I use director as router in expressjs

I want to use express.js with Flatiron's director (router) and Resourceful (ODM) because I need like the benefits of routing tables and clean multi-db schemas with validation.
The reason why I now completly switch to Flatiron is, is because I think it needs some more time and there is not much doc material.
However, that is the current way I use director in express:
var express = require('express')
, director = require('director');
function hello(){
console.log('Success');
}
var router = new director.http.Router({
'/': {
get: hello
}
});
Unfortunatly this doesn't work and gives me just a "Cannot GET /"
So what's to do?
var express = require('express')
, director = require('director')
, http = require('http');
var app = express();
var hello = function () {
this.res.send(200, 'Hello World!');
};
var router = new director.http.Router({
'/': {
get: hello
}
});
var middleware = function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err == undefined || err) next();
});
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(middleware);
app.use(express.static(__dirname + '/public'));
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
There is a sample app using express, resourceful and director here.
If you have more doubts, you can ask them in our IRC room #nodejitsu on freenode.
First, in order to use director you need to wrap it up as a middleware and pass it to express, like so:
app.use(function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err) {
// handle errors however you like. This one is probably not important.
}
next();
});
};
Aside from that: You don't need director to use resourceful, and express has its own router (so you may not even need/want director).

Resources