angular params and express hits wrong req url - javascript

anytime I add a param or query on any angular route, my browser request adds that param to the url request for my css file as such.
I am using html5mode true (pretty urls)
.state('profile', {
url: "/profile/:steamId",
templateUrl: "app/profile/profile.html",
controller: "ProfileCtrl",
controllerAs: "profile",
data: {
contentPages: 1
}
});
$locationProvider.html5Mode(true);
My angular service
getProfile:function(steamId){
var self = this;
return $http.get('api/user/'+steamId).then(function(response){
$log.debug('getProfile', response.data);
return response.data;
}, function(err){
$log.error('Error user', err);
});
},
and in my server
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Launch ======================================================================
var server = app.listen(8000, function(){
logger.info('The dagger flies at 8000');
});
// Configuration ======================================================================
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
// Routes ======================================================================
var users = require('./routes/users.route')(passport, logger);
// Middleware ======================================================================
app.use('/api/users', users);
app.get('/*', function(req, res, next) {
res.sendFile('index.html', { root: 'public' });
});
my index.html is set up for this
<link rel="stylesheet" href="builds/style.css"/>
Normally I see something like this in my network tab when I'm on localhost:8000/profile for example
http://localhost:8000/builds/style.css
but when I add a param like this
localhost:8000/profile/13456
In my network tab, I see this
http://localhost:8000/profile/builds/style.css
and therefore a bunch of unstyled html code.
How can I fix this? I have tried playing around with the express static middleware but no success.

Linking CSS or JavaScript is relative to your current directory. To overcome that, add a / in front of the path to reference it as absolute path:
<link rel="stylesheet" href="/builds/style.css"/>

Related

error when trying to use express in a controller

I've been trying to implement a paymentCtrl to handle the Stripe payments but am unable to get the express to work. When i execute this code i get the following error below. I'm quite new to this and would like to understand why i get this error.
error:
Unknown provider: appProvider <- app <- paymentCtrl
app.js:
angular.module('userApp', ['appRoutes', 'userControllers', 'userServices', 'ngAnimate', 'mainController', 'authServices', 'managementController', 'paymentController'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptors');
});
payment.html:
<div>
<form action="/charge" method="post">
<script
src="https://checkout.stripe.com/checkout.js"
class="stripe-button"
data-key="pk_test_..."
data-amount="3000"
data-name="walla"
data-description="this is not a dog"
data-locale="auto"
data-currency="gbp"
></script>
</script>
</form>
</div>
paymentCtrl:
angular.module('paymentController', [])
.controller('paymentCtrl', function(app, passport) {
app.post('/charge', function(req, res){
});
});
server.js:
var express = require('express'); // ExperssJS Framework
var app = express(); // Invoke express to variable for use in application
var port = process.env.PORT || 8080; // Set default port or assign a port in enviornment
var morgan = require('morgan'); // Import Morgan Package
var mongoose = require('mongoose'); // HTTP request logger middleware for Node.js
var bodyParser = require('body-parser'); // Node.js body parsing middleware. Parses incoming request bodies in a middleware before your handlers, available under req.body.
var router = express.Router(); // Invoke the Express Router
var appRoutes = require('./app/routes/api')(router); // Import the application end points/API
var path = require('path'); // Import path module
var passport = require('passport'); // Express-compatible authentication middleware for Node.js.
var social = require('./app/passport/passport')(app, passport); // Import passport.js End Points/API
var stripe = require('stripe')('sk_test_...');
app.use(morgan('dev')); // Morgan Middleware
app.use(bodyParser.json()); // Body-parser middleware
app.use(bodyParser.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(express.static(__dirname + '/public')); // Allow front end to access public folder
app.use('/api', appRoutes); // Assign name to end points (e.g., '/api/management/', '/api/users' ,etc. )
//
// <---------- REPLACE WITH YOUR MONGOOSE CONFIGURATION ---------->
//
mongoose.connect('mongodb://localhost:27017/tutorial', function(err) {
if (err) {
console.log('Not connected to the database: ' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
// Set Application Static Layout
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
// Start Server
app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
Your angular controller should be injected with $http module, app is undefined in your client side code as client side would not inherit code from your server.
$http module contains .post method along side numerous other methods such as .get .put .delete etc.
angular.module('paymentController', [])
.controller('paymentCtrl', function(app, passport, $http) {
$http.post('/charge', {}, function(req, res){
});
});
The second parameters in the $http.post ({}) is the data you want to transmit to your controller.
Lastly, you need a server method which will retrieve the POST request.
app.post('/charge', function(req, res) {
// Your server endpoint for /charge POST action
// req.body contains passed data.
});
As you're trying to send data using Angular to your server, you'll need to bind the form data to your model, and remove the form or listen to form submit event and make a POST request yourself the way you want to.
As you have not included the whole HTML document, it is hard to see if there are any other errors included, such as missing ng-controller declaration in your document as comments stated.
I assume you followed this Stripe tutorial so all you need to do is:
The code you've written in paymentCtrl should be copied into server.js before app.listen
// Set Application Static Layout
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
app.post('/charge', function(req, res){});
// Start Server
app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
Unknown provider: appProvider <- app <- paymentCtrl
This means that app variable you are trying to inject does not exist in your client side code.

Data undefined at Node.js from AngularJS POST request

I am attempting to send a fairly simple POST request to my server using AngularJS. The request goes through and hits my controller on the back end, but for some reason req.data is showing up as undefined.
Front End Controller:
function CardDirectiveController($http, $scope) {
var self = this;
self.addToFavorites = function() {
let card = {
id: $scope.$id,
attack : $scope.attack,
cost: $scope.cost,
img: $scope.img,
name: $scope.name,
class: $scope.class,
rarity: $scope.rarity,
type: $scope.type
}
return $http({
method: 'POST',
url: '/card',
data: card
})
};
}
angular.module('cardDirective').controller('CardDirectiveController', CardDirectiveController);
Server
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// Use any routing rules found in the router file
app.use('/', router);
app.use('/card', cardRouter)
app.listen(PORT, function() {
console.log('Application live and running on port: ' + PORT);
});
Router:
'use strict';
let express = require('express'),
cardController = require('./../controllers/cardController');
let router = express.Router();
router.route('/').post(cardController.postCard);
router.route('/:cardName').get(cardController.showCards);
module.exports = router;
Back End Controller
'use strict';
let cardController = {
showCards: showCards,
postCard: postCard
};
module.exports = cardController
function showCards(req, res) {
console.log('showCards ', req.params.cardName);
res.end()
}
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.data)
res.end()
}
The response I am getting in the console from making this request is postCard / POST undefined. Console logging the card object returns the expected result. I feel like I must be missing something obvious, but I've been stuck for a while now.
You need to use bodyParser middleware to parse request body.
Install the body-parser module:
$ npm install body-parser
Configure it in app.js :
var bodyParser = require('body-parser');
// parse application/json
app.use(bodyParser.json());
In your controller use req.body instead of req.data:
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.body);
res.end();
}
Please use body-parser in your app.js file.
Change your server.js file to following code
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter'),
bodyParser = require('body-parser');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// parse application/json
app.use(bodyParser.json());
// Use any routing rules found in the router file
app.use('/', router);
app.use('/card', cardRouter)
app.listen(PORT, function() {
console.log('Application live and running on port: ' + PORT);
});

ExpressJS export routes in external file not working for root path

I want to export my routes in external files.
Everything but the root route is working:
localhost/login -> "Login page"
localhost/ -> empty
server.js:
// SET UP =============
var express = require("express");
var app = express();
var port = 80;
var bodyParser = require("body-parser");
// CONFIG =============
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// ROUTES =============
var base = require("./routes/base");
app.use("/",base);
// LISTEN =============
app.listen(port);
console.log("Server listening on port " + port);
base.js:
var express = require('express')
var router = express.Router()
//Home
router.get('/', function (req, res) {
res.send('Home page')
})
//Login
router.get('/login', function (req, res) {
res.send('Login page')
})
module.exports = router
You don't need to specify the route on app.use('/', base) instead just supply the router middleware directly to your express app and let the router within base handle the request.
app.use(base)
Uhm, okay I found my problem.
There is an empty index.html in my ./public folder.
You're overwriting the root route with your /login route and only exporting the /login one because of that. If you want to keep all routes in one file I recommend doing something in you base.js file like:
module.exports = function(server){
server.get('/', function(request, response){
response.send('Home page.');
});
server.get('/login', function(request, response){
response.send('Login page.');
});
}
Then in the server.js file import the route using:
require('./routes/base.js')(app);
This immediately imports the routes and calls their functionality on the Express server you crated :)

Angular2 Routing in conjunction to Express routing?

My angular2 app's routes don't work when accessed via URL... Express is rendering an error page instead.
So I have one route (/docs) which serves some static content and some other static resources, however, / is routed to an index.html which is managed by angular 2. So by opening the application root and then clicking various router links I can get to a route e.g. /tutorial/chapter/1. However, as that isn't a registered route in my express app, if I refresh the page I get a 404.
I want to be able to type http://localhost:3000/tutorial/chapter/1 into my browser and get that page. How do I set express to route all undefined routes to angular, and let angular handle the 404?
Here is my app.js:
var app = express();
// html view engine setup
app.set('views', path.join(__dirname, '/ng2/views'));
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');
app.use(express.static('ng2/views'));
app.use(express.static('ng2/public'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'ng2/public', 'favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//all static assetes for hexo content
app.use('/docs', serveStatic('features/docs/public', { 'index': ['index.html', 'index.htm'] }));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
You can see the full repo here
Here is the routes middleware def:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Angular 2 assumes that independent of the request URL, the frontend will be returned. This assumption is based on a feature modern browsers implement called push state. You have 3 options if you want to support anything but the bleeding edge of browsers:
Recommended: Seperate the API server from the client.
If you put your client on example.org and your express backend on api.example.org you can just do what Angular assumes to be true. You can also deploy independently and the client can live on a static host or CDN. This will require that you setup CORS though.
Catch-All Express Route
Make sure all your routes in Express differ from the ones you setup in NG2 and make a catch-all handler. Put something like this at the end of your routes/middleware but before the 404 handler!
app.use(function(req, res, next) {
res.sendFile("index.html");
})
Use legacy browser-url-styles for the router.
You can make the NG2 router use hashes for routes. Check here.
app.js
Since order is important and new code is inserted in multiple locations, the whole file is included. Look for comment started with // JS -
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var serveStatic = require('serve-static')
var file = require('./features/prepareTutorial');
var routes = require('./ng2/routes/index');
var app = express();
// html view engine setup
app.set('views', path.join(__dirname, '/ng2/views'));
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');
app.use(express.static('ng2/views'));
app.use(express.static('ng2/public'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use('/persist', express.static(__dirname + '/persist'));
// JS - Add /app
app.use('/app', express.static(__dirname + '/ng2/views/app'));
// I have to comment this line because it failed
//file.processTutorial(); //generate html rendered patches for tutorial steps
//file.genGit(); //generate git SHA
file.processChapters();
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'ng2/public', 'favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//all static assetes for hexo content
app.use('/docs', serveStatic('features/docs/public', { 'index': ['index.html', 'index.htm'] }));
//app.use(subdomain('docs', express.static('docs/public')));
app.use('/script', serveStatic('features/docs/public/script'));
app.use('/style', serveStatic('features/docs/public/style'));
app.use('/images', serveStatic('features/docs/public/images'));
app.use('/diff', serveStatic('features/tutorial/diffs'));
app.use('/git', serveStatic('features/git'));
app.use('/chapter', serveStatic('ng2/views/app/tutorial/chapter/chapters'));
app.use('/img', serveStatic('features/docs/source/img'));
app.use('/config', serveStatic('ng2/config'));
app.use('/', routes);
// JS - /tutorial static
//app.use('/tutorial', express.static('ng2/views/app/tutorial'));
// JS - /tutorial/chapter/* send index file
app.all(/^\/tutorial$/, (req, res) => {
res.redirect('/tutorial/');
});
app.use('/tutorial/', (req, res) => {
res.sendFile(__dirname + '/ng2/views/index.html');
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
ng2/config/systemjs.config.js & ng2/public/config/systemjs.config.js
Use absolute path
This is the main issue. With relative path, the browser is requesting files at tutorial/chapter/2/app/*, tutorial/chapter/2/node_modules/*, etc, and the app break down completely.
// snip ...
var map = {
'app': '/app', // 'dist',
'#angular': '/node_modules/#angular',
'angular2-in-memory-web-api': '/node_modules/angular2-in-memory-web-api',
'rxjs': '/node_modules/rxjs'
};
// snip ...
ng2/views/index.html
Use absolute path
This won't stop the page from loading but a mess.
// snip ...
<link rel="stylesheet" href="/stylesheets/style.css">
// snip ...
Instead of app.use('/', routes);, register a middleware that will always serve the index.html. Be cautious though, this can cause your app to return index.html even inside the /docs route.
Just use the middleware that renders the index page:
app.use(routes);
Make sure the routes middleware itself always renders the page, not only on / path.
var express = require('express');
/* render home page. */
var router = function(req, res, next) {
res.render('index', { title: 'Express' });
};
module.exports = router;
Remove this the 404 handler (it should be automatic)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
And change the node_modules route to the following (because SystemJS relies on 404 responses during resolution):
var modules = express.Router();
modules.use(express.static(__dirname + '/node_modules'));
modules.use(function(req, res, next) {
// Missing files inside node_modules must return 404
// for the module loader to work
res.sendStatus(404);
});
app.use('/node_modules', modules);

How to fetch images from node.js server's folder in URL?

Does anybody know how to fetch images from node.js server's folder in URL?
In my folder structure I have folder data and inside there is subfolder img with image. I want to access this image with URL, like this:
http://localhost:3000/data/img/default.jpg
but when I enter it into browser I always get this error:
Page Not Found /data/img/default.jpg is not a valid path.
server.js:
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose');
var express = require('express');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error('\x1b[31m', 'Could not connect to MongoDB!');
console.log(err);
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
app.use(express.static('data/img'));
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
express.js:
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
session = require('express-session'),
compress = require('compression'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
helmet = require('helmet'),
passport = require('passport'),
mongoStore = require('connect-mongo')({
session: session
}),
flash = require('connect-flash'),
config = require('./config'),
consolidate = require('consolidate'),
path = require('path');
module.exports = function(db) {
// Initialize express app
var app = express();
// Globbing model files
config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
require(path.resolve(modelPath));
});
// Setting application local variables
app.locals.title = config.app.title;
app.locals.description = config.app.description;
app.locals.keywords = config.app.keywords;
app.locals.facebookAppId = config.facebook.clientID;
app.locals.jsFiles = config.getJavaScriptAssets();
app.locals.cssFiles = config.getCSSAssets();
// Passing the request url to environment locals
app.use(function(req, res, next) {
res.locals.url = req.protocol + '://' + req.headers.host + req.url;
next();
});
// Should be placed before express.static
app.use(compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Showing stack errors
app.set('showStackError', true);
// Set swig as the template engine
app.engine('server.view.html', consolidate[config.templateEngine]);
// Set views path and view engine
app.set('view engine', 'server.view.html');
app.set('views', './app/views');
// Environment dependent middleware
if (process.env.NODE_ENV === 'development') {
// Enable logger (morgan)
app.use(morgan('dev'));
// Disable views cache
app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') {
app.locals.cache = 'memory';
}
// Request body parsing middleware should be above methodOverride
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// Enable jsonp
app.enable('jsonp callback');
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
// connect flash for flash messages
app.use(flash());
// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
// If the error object doesn't exists
if (!err) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not Found'
});
});
return app;
};
It's like you have already set your data/img folder as a static folder in the line below:
app.use(express.static('data/img'));
In that case, you should be accessing images placed in the static folder above using below url:
http://localhost:3000/default.jpg
I will however advice you use Node's global variable __dirname to indicate the root of the static folder but this depends on where your server.js is located within your file structure.
The js file containing the snippets below is located in the root and I have /data/img folder from the root as well and I am able to retrieve the image using /image name.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/data/img'));
app.listen(3500, function () {
console.log('Express server is listening, use this url - localhost:3500/default.png');
});
See if this helps you. If it does, make sure you know the reason for using the __dirname global variable name.
SO1

Categories