Axios post error - reactjs

I am trying to post to my api endpint, I get the error:
Uncaught (in promise) Error: Network Error
at createError (C:\sites\LYD\node_modules\axios\lib\core\createError.js:16)
at XMLHttpRequest.handleError (C:\sites\LYD\node_modules\axios\lib\adapters\xhr.js:87)
My axios post is:
submitForm(UserDetails) {
let self = this;
self.show();
axios
.post('http://localhost:3001/api/users', UserDetails)
.then(function(response) {
self.hide();
});
}
My node error is:
C:\sites\LYD>node server
api running on port 3001
(node:11808) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:555:11)
at C:\sites\LYD\server\index.js:75:20
at C:\sites\LYD\node_modules\mongoose\lib\model.js:3809:16
at C:\sites\LYD\node_modules\mongoose\lib\services\model\applyHooks.js:164:17
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Any ideas?
My server.js is:
//first we import our dependencies...
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('../models/users');
//and create our instances
const app = express();
const router = express.Router();
//set our port to either a predetermined port number if you have set it up, or 3001
const port = process.env.API_PORT || 3001;
//db config -- REPLACE USERNAME/PASSWORD/DATABASE WITH YOUR OWN FROM MLAB!
const mongoDB =
'mongodb://dxxx#aws-eu-west-1-portal.4.dblayer.com:10204/xxx?ssl=true';
mongoose.connect(mongoDB, { useMongoClient: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//now we should configure the APi to use bodyParser and look for JSON data in the body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,HEAD,OPTIONS,POST,PUT,DELETE'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!' });
});
//adding the /comments route to our /api router
router
.route('/users')
//retrieve all comments from the database
.get(function(req, res) {
//looks at our Comment Schema
User.find(function(err, users) {
if (err) res.send(err);
//responds with a json object of our database comments.
res.json(users);
});
})
//post new comment to the database
.post(function(req, res) {
var NewUser = new User();
req.body.accessCode ? (NewUser.accessCode = req.body.accessCode) : null;
req.body.age ? (NewUser.age = req.body.age) : null;
req.body.drinkConcern
? (NewUser.drinkConcern = req.body.drinkConcern)
: null;
req.body.drinkOften ? (NewUser.drinkOften = req.body.drinkOften) : null;
req.body.ethnicity ? (NewUser.ethnicity = req.body.ethnicity) : null;
req.body.gender ? (NewUser.age = req.body.gender) : null;
req.body.language ? (NewUser.language = req.body.language) : null;
NewUser.save(function(err) {
if (err) res.end(err);
res.json({ message: 'Comment successfully added!' });
});
});
//Adding a route to a specific comment based on the database ID
router
.route('/users/:id')
//The put method gives us the chance to update our comment based on the ID passed to the route
.put(function(req, res) {
Comment.findById(req.params.id, function(err, user) {
if (err) res.send(err);
//setting the new author and text to whatever was changed. If nothing was changed
// we will not alter the field.
req.body.author ? (comment.author = req.body.author) : null;
req.body.text ? (comment.text = req.body.text) : null;
//save comment
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'Comment has been updated' });
});
});
})
//delete method for removing a comment from our database
.delete(function(req, res) {
//selects the comment by its ID, then removes it.
User.remove({ _id: req.params.comment_id }, function(err, user) {
if (err) res.send(err);
res.json({ message: 'Comment has been deleted' });
});
});
//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
I have changed my axios post to this:
let self = this;
self.show();
const headers = {
'Content-Type': 'application/json',
};
axios
.post('http://localhost:3001/api/users', UserDetails, headers)
.then(function(response) {
self.hide();
});

You can change the mongoose query to,
let query = {} //or any other query
User.find(query,function(err,res){
...
})

I think the problem is with your routes.
When you create a route instead of using router.route('/route').post(function(req, res) { ... }, use router.post('/route', function(req, res) { .... } (obviously change .post to the method you want to use)
In your code this would be:
router
.get('/users', function(req, res) {
User.find(function(err, users) {
if (err) res.send(err);
res.json(users);
});
})
I think you can only do app.route('/route').get(...).post(...) but not with router
Look at the express routing documentation for more info: https://expressjs.com/en/guide/routing.html

Related

How to set up API server for multiple fetch requests of SQL Server data?

I'm new to react, and I want to set up an API server to get SQL Server data, and I want to send multiple fetch requests to the API server.
I've tried the promise.all method, but it's always failing on the second fetch request. The only way I could make it work is by nesting the requests through.then, but I prefer not to, since the number of fetch requests are varied.
Here's my code:
Promise.all([
//the number of requests varied
fetch('http://localhost:8080/api/report/favorite/check/1/1').then(value => value.json()),
fetch('http://localhost:8080/api/report/favorite/check/1/4').then(value => value.json())
])
.then((value) => {
//I always get EALREADYCONNECTING error here from 2nd request and on
console.log(value)
})
.catch((err) => {
console.log(err);
});
Does the problem lie in the API server configuration?
//Initializing node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
// Body Parser Middleware
app.use(bodyParser.json());
//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
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, contentType,Content-Type, Accept, Authorization");
next();
});
//Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
var connPool = new sql.ConnectionPool({
user: 'someuser',
password: 'somepassword',
server: 'some\\thing',
database: 'somedb',
port: 12345
});
//Function to connect to database and execute query
var executeQuery = function(res, query){
connPool.connect().then(function () {
// create request object
var request = new sql.Request(connPool);
// query to the database
request.query(query).then(function (recordset) {
res.send(recordset)
connPool.close();
})
.catch(function (err) {
console.log("Error while querying database :- " + err);
res.send(err)
connPool.close();
});
})
.catch(function (err) {
console.log("Error while connecting database :- " + err);
res.send(err);
});
}
//GET API
app.get("/api/report/favorite/check/:userid/:reportid", function(req, res){
var query = "EXEC rpt.proc_ReportFavoriteCheck " + req.params.userid + ", " + req.params.reportid;
executeQuery (res, query);
});
I tried several methods, as described here, but I can't make it work:
Fetch API requesting multiple get requests
Multiple fetch requests with setState in React
How to finish Fetch data completely and assign it to component state before proceeding further in componentDidMount React?
Solved this by changing my API server configuration:
var executeQuery = async function(res, query){
const pool = new sql.ConnectionPool(dbConfig);
pool.on('error', err => {
console.log('sql errors ', err);
});
try {
await pool.connect();
let result = await pool.request().query(query);
console.log('success')
res.send(result);
return {success: result};
} catch (err) {
console.log('error')
console.log(err)
res.send(err);
return {err: err};
} finally {
pool.close();
}
}

HTTP requests fail for AngularJS/Express using Mongoose when it works with MongoJS

Need some help figuring out whats wrong with my code that's giving me 500 internal server error. Have been trying to figure out root cause myself since last 3 days to no avail. I've started learning the MEAN stack and have been experimenting with MongoJs and Mongoose. It's the latter setup that is not working. I've pasted below
a) gulpfile.js
b) Mongoose model/schema file (modelA.js),
c) httprequests.js file containing http requests using mongojs and mongoose {on the sideline - is it a bad idea to have MongoJS and Mongoose codes in the same application???} and
d) angular script file (phone.js) . With the current coding my page (not mentioned below) using mongojs is working perfectly.
e) Error messages from Terminal and Chrome console
I'm new to MEAN and must be doing something basically wrong. Any help is sincerely appreciated.
Gulpfile.js:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
// historyapifallback to help overcome page refersh issue in angularjs
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
port: 3001,
proxy: {
target: "localhost:3000",
ws: true,
middleware: [ historyApiFallback() ]
}
});
gulp.watch("./**/*.*").on('change', browserSync.reload);
});
gulp.task('default',['serve'], function() {
var httpRequests = require('./scripts/mongo-mongodb/httprequests');
});
modelA.js
var mongoose = require('../../../node_modules/mongoose/lib');
var Schema = mongoose.Schema;
var phoneSchema = new Schema({
age : Number,
carrier : String,
id : String,
imageUrl : String,
name : String,
company: String,
snippet : String
});
/* global db */
module.exports = mongoose.model('Phone', phoneSchema);
httprequests.js
// load express module
var express = require("express");
// bootstrap express
var app = express();
//serve up index.html
app.use(express.static("./"));
// body parser for post requests
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Mongojs codes follows...
var mongojs = require('mongojs');
var db = mongojs('test',['technology']);
// get all data from db
app.get('/techstack',function(req,res) {
db.technology.find({},function(err,docs) {
if (err) throw err;
// console.log("im here");
// console.log(docs);
res.json(docs);
});
});
// get data from db for specific id
app.get('/techstack/:id',function(req,res) {
var id = req.params.id;
db.technology.findOne({_id: mongojs.ObjectId(id)},function(err,docs) {
if (err) console.error;
console.log(id);
console.log("gulpfile");
res.json(docs);
});
});
app.post('/techstack', function(req,res) {
console.log(req.body);
db.technology.insert(req.body,function(err,docs) {
if (err) console.error;
res.json(docs);
});
});
app.delete('/techstack/:id', function(req,res) {
var id = req.params.id;
db.technology.remove({_id: mongojs.ObjectId(id)},function(err,docs) {
// console.log(id);
// db.technology.remove({ _id: id},function(err,docs) {
if (err) console.error;
res.json(docs);
});
});
app.put('/techstack/:id', function(req,res) {
var id = req.params.id;
db.technology.findAndModify(
{
query: {_id:mongojs.ObjectId(id)},
update: {$set: {sl:req.body.sl, name:req.body.name, status:req.body.status, complexity:req.body.complexity}},
new: true
}, function (err, docs) {
if (err) console.error;
res.json(docs);
});
});
//
// Mongoose codes follow...
var mongoose = require('../../../node_modules/mongoose/lib');
mongoose.connect('mongodb://localhost/mean_db');
// var uri ='mongodb://localhost/mean_db';
// global.db = mongoose.createConnection(uri);
// var routes = require('../mongo-mongoose/routes');
var Phone = require('./modelA');
var router = express.Router(); // get an instance of the express Router
// // middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/',function(req,res) {
Phone.find({},function(err, docs) {
if (err)
res.send(err);
res.send(docs);
});
});
router.post('/',function(req, res) {
var phone = new Phone(); // create a new instance of the Phone model
// save the phone and check for errors
phone.save(req.body,function(err,docs) {
if (err)
res.send(err);
res.json(docs);
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /phone-list
app.use('/phone-list', router);
app.listen(3000);
console.log('Listening on port 3000');
phone.js
'use strict';
var phone = angular.module('phone',[]);
phone.controller('View1Ctrl', function($scope,$http,$log,$location) {
$scope.phone = {
age : 0,
carrier : "",
id : "",
imageUrl : "",
name : "",
company: "",
snippet : ""
};
$http.get('/phone-list')
.then(function (response) {
// console.log(response.data);
$scope.phoneList = response.data;
}
);
$scope.insertPhone = function () {
$http.post('/phone-list', $scope.phone)
.then(function (response) {
console.log("inside post in phone.js");
$scope.phoneList = response.data;
$route.reload();
});
};
Error Messages:
On terminal
14:18:51] Using gulpfile ~/github/mean-project/app/gulpfile.js
[14:18:51] Starting 'serve'...
[14:18:52] Finished 'serve' after 129 ms
[14:18:52] Starting 'default'...
Listening on port 3000
[14:18:52] Finished 'default' after 686 ms
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
----------------------------------
Local: http://localhost:3001
External: http://10.0.1.12:3001
----------------------------------
UI: http://localhost:3003
UI External: http://10.0.1.12:3003
----------------------------------
Something is happening.
Something is happening.
Something is happening.
Something is happening.
Something is happening.
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^ TypeError: callback is not a function
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/lib/model.js:228:5
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/lib/model.js:135:7
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/collection.js:504:5
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/collection.js:666:5
at handleCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at /Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:473:9
at handleCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12)
at resultHandler (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:420:5)
at commandCallback (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1194:9)
at Callbacks.emit (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at null.messageHandler (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:358:23)
at Socket.<anonymous> (/Users/akhileshmohan/github/mean-project/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:292:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
On browser console
angular.js:12011 POST http://localhost:3001/phone-list net::ERR_EMPTY_RESPONSE
(anonymous function) # angular.js:12011
n # angular.js:11776
(anonymous function) # angular.js:11571
(anonymous function) # angular.js:16383
$eval # angular.js:17682
$digest # angular.js:17495
$delegate.__proto__.$digest # VM95:844
$apply # angular.js:17790
$delegate.__proto__.$apply # VM95:855
(anonymous function) # angular.js:25890
Sf # angular.js:3497
d # angular.js:3485

Angularjs CORS trouble with Node, Express, Oauth2, and Passport

Recently we have decided to switch our front-end from EJS to Angular separate the frontend and the backend completely. In doing so, we started to run into several issues across multiple browsers. On the back end we are using Node with express along with passport and oauth2. For the front end we are attempting to use angular. EJS works using express.render, but we would prefer to use angular directly by utilizing express as just a RESTful API.
I'm running both the backend and frontend locally at localhost:8080 and localhost:3000, respectfully. When just working with the backend (USING EJS, NOT ANGULAR), I can successfully go to our backend port in the browser, login via passport-oauth, and be redirect to the account page (from the providers login screen) where my json data is rendered via res.json. The problem is I am unable to do this from the frontend UI after removing EJS.
I've tried configuring CORS a dozen different ways while using three different browsers with no luck. The following three snippets are the errors I'm getting in the browsers console while trying to access localhost:8080 from the frontend via $http and $resource (see below for the code). The image below the three code snippets is what the node console is telling me when trying to access port 8080 from each different browser...
Chrome:
XMLHttpRequest cannot load 'PROVIDER-DETAILS-URL'. No 'Access-Control-Allow- Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'PROVIDER-DETAILS-URL'. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'PROVIDER-DETAILS-URL'. (Reason: CORS request failed).
Safari:
XMLHttpRequest cannot load http://localhost:8080/auth/PROVIDER. Request header field Accept-Encoding is not allowed by Access-Control-Allow-Headers.
Console Image:
And the code:
Server:
app.js
'use strict';
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const path = require('path');
const flash = require('connect-flash');
const passport = require('passport');
const expressValidator = require('express-validator');
/**
* Load environment variables, where API keys and passwords are configured.
*/
const config = require('./config/config');
/**
* Route Handlers
*/
const index = require('./routes/index');
const account = require('./routes/account');
const logout = require('./routes/logout');
/**
* API keys and Passport configuration.
*/
const passportConfig = require('./strategy');
/**
* Create Express server.
*/
const app = express();
/**
* Express configuration.
*/
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT");
next();
});
app.use(cookieParser());
app.use(expressValidator());
app.use(session({
resave : true,
saveUninitialized : true,
secret : config.sessionSecret,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
/**
* Primary app routes.
*/
app.get('/', index.execute);
app.get('/account', passportConfig.isAuthenticated, account);
app.get('/logout', logout.execute);
/**
* OAuth authorization routes.
*/
app.get('/auth/PROVIDER', passport.authenticate('PROVIDER'));
app.get('/auth/PROVIDER/callback', passport.authenticate('PROVIDER', { failureRedirect : '/'}), function(req, res) {
res.redirect('/account');
});
/**
* Error Handler.
*/
app.use(errorHandler());
/**
* Start Express server.
*/
app.listen(8080, () => {
console.log('App listening on port 8080');
});
module.exports = app;
strategy.js
'use strict';
const passport = require('passport');
const session = require('express-session');
const config = require('./config/config');
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
/**
* Put together the right header info for PROVIDER
*/
var authString = new Buffer(config.PROVIDER.clientID + ':' + config.PROVIDER.clientSecret);
var customHeader = {
"Authorization": "Basic " + authString.toString('base64')
};
/**
* OAuth2Strategy containing the customHeader created above.
*/
passport.use('PROVIDER', new OAuth2Strategy({
authorizationURL : config.PROVIDER.authorizationURL,
tokenURL : config.PROVIDER.tokenURL,
clientID : config.PROVIDER.clientID,
clientSecret : config.PROVIDER.clientSecret,
callbackURL : config.PROVIDER.callbackURL,
customHeaders : customHeader,
passReqToCallback : true
},
function( req, accessToken, refreshToken, profile, done ) {
req.session.accessToken = accessToken;
return done(null, profile);
}
));
passport.serializeUser(function(user, done) {
return done(null, user);
});
passport.deserializeUser(function(obj, done) {
return done(null, obj);
});
/**
* Login Required middleware.
*/
exports.isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
console.log('isAuthenticated');
return next();
}
res.redirect('/');
};
/**
* Authorization Required middleware.
*/
exports.isAuthorized = function(req, res, next) {
var provider = req.path.split('/').slice(-1)[0];
if (_.find(req.user.tokens, { kind: provider })) {
next();
} else {
res.redirect('/auth/' + provider);
}
};
index.js
exports.execute = function (req, res) {
if (req.user) {
console.log('========== ROUTES/INDEX.JS | 3 ==========');
res.redirect('/account');
} else {
console.log('========== ROUTES/INDEX.JS | 6 ==========');
res.redirect('/auth/PROVIDER');
}
};
Client:
I combined this to make it a little easier to read.
angular.module('StackOverflowPost', [])
.factory('APIService', function() {
function getData( $q, $http ) {
var defer = $q.defer();
$http.get( 'localhost:8080' )
.success( getDataComplete )
.catch( getDataFailed );
function getDataComplete( response ) {
console.log( response.Authorization );
defer.resolve(response.data.results );
}
function getDataFailed( error ) {
console.log( error.data );
defer.reject( 'XHR Failed for getData - ' + error.data );
}
return defer.promise;
}
})
.controller('MainCtrl', function( APIService ) {
var vm = this;
vm.getDataTest = function() {
APIService.getData().then(function( returnedData ) {
console.log( returnedData );
})
}
});
Any help or direction would be greatly appreciated.
UPDATE (4/28/2016): I updated the original post with more details. I also updated the code to what it is after another week of trial and error.
Please check this
https://gist.github.com/dirkk0/5967221
Code should be
// in AngularJS (client)
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
// in Express/nodeJS
// in NodeJS/Express (server)
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});

How do I process responses from express with angular?

This is for a project for college. I am having difficulty understanding how to handle express responses with angular. My partner handled most of the back end and I took care of most of the front end, as to how to get information from express and use it on the front end. Our routing is below, if it will help.
// set variables for environment
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
//tell express to use the bodyParser middleware
app.use(bodyParser());
//start the mysql interface
var mysql = require('mysql');
var mysql = require('mysql');
var connectionPool = mysql.createPool({
host : 'localhost',
user : '<user>',
password : '<password>',
database : '<table>'
});
// connection.connect();
// connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
// });
// connection.end();
// Set server port
app.listen(80);
console.log('server is running at 127.0.0.1:80');
// views as directory for all template files
app.set('views', path.join(__dirname, 'views'));
// instruct express to server up static assets
app.use(express.static('public'));
// set routes
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/:file', function(req, res) {
res.sendFile(__dirname + '/views/' + req.params.file);
});
app.get('/req/:itemname', function(req,res)
{
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
else
{
var query = 'SELECT * FROM Product WHERE name LIKE \'%' + req.params.itemname +'%\' ORDER BY ProductID asc';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
res.send({
result: 'success',
err: '',
fields: fields,
json: rows,
length: rows.length
});
}
});
connection.release();
}
});
// connection.destroy();
});
app.post('/login/', function(req,res)
{
//debug for routes to make sure everything is working properly
console.log('I am in the login post route');
//connect to SQL pool
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error, having issue connecting to MYSQL DB instance',
err: err.code
});
}
else
{
var user = req.body.email;
user = user.toUpperCase();
var password = req.body.password;
console.log('user: ' + user);
console.log('password: ' + password);
var query = 'select COUNT(*) AS recordCount, isStaff from userTable where email = \''+user+'\' AND password = \''+password+'\'';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
//another connection issue
console.log('in 500 error box')
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
//if the query was successful, we check to see if their exists a record of this query
//debug print count of records that match parameters
// console.log(rows[0].recordCount)
//if the return query has a user that has admin privileges, redirect them to the admin page
console.log(rows[0].isStaff);
if(rows[0].recordCount >=1 && rows[0].isStaff == 1)
{
console.log('at least one staff record')
res.sendFile(__dirname + '/views/admin.html')
// next();
}
else if(rows[0].recordCount >=1 && rows[0].isStaff == 0)
{
console.log('at least one nonstaff record')
res.sendFile(__dirname + '/views/customer.html')
// next();
}
else
{
console.log('invalid login')
console.log('in 503 error box, invalid user')
res.statusCode = 503;
res.send({
statuscode: '503',
result: 'E-mail or Password is incorrect',
});
}
}
});
connection.release();
}
});
});
Near the bottom of the code we specifically would like to handle the case when we have a login error. Right now it just sends back {{ statuscode: 503, result: 'E-mail or Password is incorrect'}} on a blank page.
On the front end a modal is displayed requesting sign in information. On success it redirects to a different page. On failure we would like to tell the front end to leave the modal on the page open and post an alert message in the body of the modal.
Please help.
Edit: The purpose of the project is working with the database. The project requires a web based app as the interface and since our next course requires using the MEAN stack we decided to go ahead and start learning a bit on our own.
In your $http call on the frontend, simply pass in a second argument as you error handling callback. The $http service will run that function any time the server sends back an error status.
https://docs.angularjs.org/api/ng/service/$http
$http.get('api/route')
.then(function successCallback(response) {
loginSuccessRedirect();
}, function errorCallback(response) {
handleLoginError();
});

Trouble with getting data from nodejs/express because of CORS

Solution here: Trouble with getting data from nodejs/express because of CORS
So i have a problem with getting data from nodejs/express because of CORS.
I'm getting error something like this (sorry, error i translated with google):
Query from an external source is blocked: one source of policy prohibits reading remote resource on http://localhost:8080/api/login. (Cause: Failed to query CORS).
I'm trying to send query with angular $http.post
$http.post($rootScope.api + 'login', {
email: form.email.$viewValue,
password: form.password.$viewValue
}).then(function(data) {
console.log(data.data);
});
Here is my server code (i cut some code, because i think it not important):
/* some nodejs requires */
var cors = require('express-cors');
mongoose.connect('mongodb://localhost:27017/batarindashboard');
require('./config/passport')(passport);
/* some express settings */
app.use(cors({
allowedOrigins: [
'localhost:*', '127.0.0.1:*'
]
}));
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening');
next();
});
/* sign up api */
router.post('/login', passport.authenticate('local-login', {
failureRedirect : '/api/passport_message',
failureFlash : true
}), function(req, res) {
res.json({
'message': 'You successfully signed in!'
});
});
/* passport_message api */
/* is_logged_in api */
/* logout api */
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
And passport file (maybe problem is here. Why not?)
var LocalStrategy = require('passport-local').Strategy;
var User = require('./../app/models/user');
module.exports = function(passport) {
/* some serialize deserialize code */
/* sign up strategy */
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function(req, email, password, done) {
User.findOne({
'local.email':email
}, function(err, user) {
if(err) return done(err);
if(!user) {
return done(null, false, req.flash('message', 'No user found.'));
}
if(!user.validPassword(password)) {
return done(null, false, req.flash('message', 'Oops! Wrong password.'));
}
return done(null, user);
})
}))
};

Resources