I've been trying to understand how to set up Stripe for my app but am having problems with the implementation of the module. Normally when using a module i would require it in the top of the file to be able to use it but I'm not sure how to do this here in the paymentController file or if i even need to. I imported the Stripe npm, so does that i mean that i can access it globally? Well as you see i'm quite new to this and would like to understand how to structure this so that the payments work.
app.js file:
angular.module('userApp', ['appRoutes', 'userControllers', 'userServices', 'ngAnimate', 'mainController', 'authServices', 'managementController', 'paymentController'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptors');
});
paymentController file:
angular.module('paymentController', [])
.controller('paymentCtrl', function($scope) {
var app = this;
});
Server.js file:
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
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. )
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
});
I'd recommend following what's shown for Node in this Stripe tutorial:
https://stripe.com/docs/charges
Just like your other includes, you want something like this at the top of any JS file that will use the Stripe library:
var stripe = require('stripe')('sk_my_secret_key')
Then, elsewhere in the same file, you can call any Stripe library methods you need:
stripe.charges.create(…)
Of course, in production you'll want to build a proper 12 Factor app[1] and put your secrets in environment variables or configuration files.
[1] https://12factor.net/config
Related
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.
currently developing a distributed system and crashed my code last night. My server-application has multiple modules which each established a connection to my redis db, however it would be better if there is a single connection via the main module. This, I tried to implement last night, But I can't quite figure out what exactly is the problem. I'm still quite new to this field, and already searched through pages like SitePoint, Medium, and other blogs, and also checked for my problem or derived versions of it here, but found nothing what could help me enough to settle this.
UPDATE 2016/6/24 13:18
I removed the app.use()-Statement from my code and now the server is firing up. Progress :)
However, If I try to test a route , the only reply I get is Cannot <METHOD> <ROUTE>.
Looking at this question here provides me with the answer to utilize the very app.use() I just removed from the code. Is there something I'm missing?
UPDATE 2016/6/24 14:05
I implemented the statement app.use('/', account_routing.routes);, doesn't work but seems the right way to go, doesn't it? I can send requests, but there is no answer whatsoever right now.
I'm providing the code for my server application:
main.js
var
express = require('express'),
redis = require('redis'),
app = express(),
port = process.env.port || 3000,
rclient = redis.createClient(),
account_routing = require('./modules/account_routing');
// ### CONFIGURATION ################################################
rclient.on('connect', function (err, res) {
console.log(err || "Connected to database!");
});
account_routing.setClient(rclient);
app.use('/', account_routing.routes);
// ### FIREUP #######################################################
app.listen(port, function () {
console.log('Server available at port ' + port);
});
account_routing.js
var rclient, express;
express = require('express');
module.exports = {
setClient : function (inClient) { 'use strict'; rclient = inClient; },
routes : function(app) {
// ### VARIABLES ####################################################
var bodyParser, http, morgan, redis, rclient, app;
// ### DEPENDENCIES #################################################
bodyParser = require('body-parser');
http = require('http');
morgan = require('morgan');
redis = require('redis');
app = express();
// ### CONFIGURATION ################################################
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// ### ROUTES #######################################################
app.get('/users/:username', function (req, res) {
/* Access database via connection in main module
to retrieve user data */
});
}
};
Thank you all very much in advance for help.
So basically after an awful lot of lost nerves, I stumbled upon this nice gem here.
I implemented it this very way, so now I have:
main.js
"use strict";
var
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
port = process.env.port || 3000,
account_routing = require('./modules/account_routing')(app);
app.listen(port, function () {
console.log('Server available at port ' + port);
});
redis_db.js
var
redis = require('redis'),
rclient = redis.createClient();
rclient.on('connect', function (err, response) {
'use strict';
console.log("Connected to database");
});
module.exports = rclient;
and account_routing.js
'use strict';
module.exports = function (app) {
var
bodyParser = require('body-parser'),
http = require('http'),
morgan = require('morgan'),
rclient = require('./redis_db');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(morgan('dev'));
/* Routes */
This way, there is a single connection established to the redis database, and also the routes are working properly now.
I hope this information will help somebody.
I'm a noob and working on mean.js boilerplate.
I've created some routes, but I'm having an issue, where, when I navigate to a certain route ('/articles') i get server output like this:
[{"_id":"5553aa4116a2fddc830b0f66","user":{"_id":"5552398fcf7ada7563db68b7","displayName":"Mo
Bazazi"},"__v":0,"content":"WAHATTATA","title":"Fifth
Examples","created":"2015-05-13T19:47:13.905Z"}]
but i want to ge the rendered view, even when I manually type in the route - does anyone have any suggestions?
here part of my express config
use strict';
/**
* Module dependencies.
*/
var fs = require('fs'),
http = require('http'),
https = require('https'),
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');
So Claies was right - this is an HTML5 issue - I've been working on this a little and trying to set up a catch all for express config - I've added this section below:
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
app.get('/', function(req, res) {
res.render('index');
});
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
app.get('*', function(req, res) {
res.redirect('/');
});
The problem is that I'm using mean.js boilerplate, and they have custom glob based routing, which doesn't play well with my catchall i.e. my resources wont work properly with the catchall as they are, although they are rerouting to the correct templates - any thoughts?
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
I am developing an application using the MEAN stack (Node.js, Express, AngularJS, and Mongoose). I have a basic understanding of the two. My API is running on a different port from my frontend, and because of this, I've included the CORS header in my API file. However, Chrome is still giving me this error:
XMLHttpRequest cannot load http://localhost:9000/#/.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is the header I've included in my API:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I have no idea where I'm going wrong. If it helps at all, I'm trying to load a user object in order to display information on a profile page. This is the code from my Profile Controller:
angular.module('angTestApp')
.controller('ProfileCtrl', function ($scope, $http) {
$http.get('http://localhost:8080/profile')
.success(function (user) {
$scope.user = user;
console.log(user);
});
});
EDIT
Here's my server.js file if that helps:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var cors = require('cors');
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://test:test#novus.modulusmongo.net:27017/a3pemoGa')
var classroom = require('./app/models/classroom');
var article = require('./app/models/article');
var user = require('./app/models/user');
//From Tutorial
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());
app.use(cors());
//app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
//From tutorial
// set up our express application
require('./app/config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/API/routes')(app, passport);
//require('./app/API/general');
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
//exports = module.exports = app;
i resolved the cors issue with tricky solution . first create the the route of scrape like this with require "REQUEST" npm
app.get('/scrape', function (req, res) {
console.log("=============================Scrape =========================")
var url = req.body.url;
request(url, function(error, response, html){
if(!error){
res.send(html)
}
});
and in the frontend use like this
$http.get("/scrape", {
params: { "url": "http://localhost:8080/profile" }
});