I would want to consume GET/PUT/POST/DELETE API’s through a web page (HTML) which would be integrated on the Oracle JET.
The webpage will have one input free text option, where the user can type in to update the record.
i.e. If I click on one record on the JET dashboard, the API ‘GET /alluser/:FIRST_NAME – Read the profile of an user’ will be called,
it will display the detailed record with one text box as free text,
once the user enters text and hits submit, ‘PUT /process_post – Update the profile of an user’ API will be called, which will update the record.
Here is my script
var express = require('express');
var oracledb = require('oracledb');
var app = express();
var dbConfig = require('./dbconfig.js');
var bodyParser = require('body-parser');
var port = 3000;
app.use(bodyParser.json()); // Use body parser to parse JSON body
oracledb.outFormat = oracledb.OBJECT;
// Get a non-pooled connection
function run() {
oracledb.createPool({
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err) {
if (err)
console.error("createPool() error: " + err.message);
else
var server = app.listen(port,
function () {
console.log('Server is listening on port ' + server.address().port);
});
});
}
function doGetConnection(res, cb) {
oracledb.getConnection(function (err, connection) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting DB connection",
detailed_message: err.message
}));
} else {
cb(err, connection);
console.log(" Connection is connected");
}
});
}
app.post('/process_post', function (req, res) {
console.log("contenttype"+req.get('Content-Type'))
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"INSERT INTO TEST_TABLE(FIRST_NAME,LAST_NAME) VALUES (:FIRST_NAME,:LAST_NAME)",
[(req.body.FIRST_NAME),(req.body.LAST_NAME) ],
{ autoCommit: true,
outFormat:oracledb.OBJECT
},
console.log("check2"),
function (err) {
console.log("check3");
if (err) {
console.log("check4");
res.set('Content-Type', 'application/json');
res.status(400).send(JSON.stringify({
status: 400,
message: "Input Error",
detailed_message: err.message
}));
} else {
// Successfully created the resource
res.status(201).set('Location', '/process_post/' + req.body.FIRST_NAME).end();
}
doRelease(connection, "POST /process_post");
});
});
});
app.get('/alluser', function (req, res) {
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"SELECT * from employees",
function (err, result) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting the farmer's profile",
detailed_message: err.message
}));
} else {
res.contentType('application/json').status(200);
res.send(JSON.stringify(result.rows));
}
doRelease(connection, "GET /bananas");
});
});
});
app.get('/alluser/:FIRST_NAME', function (req, res) {
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"SELECT * from employees WHERE first_name = :f",
{ f: req.params.FIRST_NAME },
function (err, result) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting the farmer's profile",
detailed_message: err.message
}));
} else if (result.rows.length < 1) {
res.set('Content-Type', 'application/json');
res.status(404).send(JSON.stringify({
status: 404,
message: "FIRST_NAME doesn't exist",
detailed_message: ""
}));
} else {
res.contentType('application/json');
res.status(200).send(JSON.stringify(result.rows));
}
doRelease(connection, "GET /user/" + req.params.FIRST_NAME);
});
});
});
function doRelease(connection, message) {
connection.close(
function(err) {
if (err)
console.error(err);
else
console.log(message + " : Connection released");
});
}
run();
Thank you.
Oracle JET can help you make API calls.
Here's an example from their Cookbook: http://www.oracle.com/webfolder/technetwork/jet/jetCookbook.html?component=crud&demo=model
Have a look at the documentation for Collection and Model.
It's a lot to read if you're getting into it for the first time, so I'll give a quick example for a GET all:
var dataModel = oj.Model.extend({urlRoot: 'example.com'});
var modelInstance = new dataModel();
var CollectionConfig = {
model: modelInstance,
url: 'example.com'
};
var dataCollection = oj.Collection.extend(CollectionConfig);
var collectionInstance = new dataCollection();
collectionInstance.fetch({
success: function (collection, response, options) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Related
I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.
This is API code
var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');
const router = express.Router();
router.get("/:userId", (req, res, next) => {
let uid = req.params.userId;
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
if(!err) {
if(data && data.length > 0) {
var message = '';
if(data.u_password){
//var pass = data.u_password;
if(bcrypt.compare('123456', data.u_password)) {
// Passwords match
message = 'Passwords match';
} else {
// Passwords don't match
message = 'Passwords dont match';
}
}
res.status(200).json({
message:message,
});
} else {
res.status(200).json({
message:"User Not found."
});
}
}
});
});
database.js
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: '',
database: 'lost_and_found',
debug : false
});
function executeQuery(sql, callback) {
pool.getConnection((err,connection) => {
if(err) {
return callback(err, null);
} else {
if(connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
return callback(error, null);
}
return callback(null, results);
});
}
}
});
}
function query(sql, callback) {
executeQuery(sql,function(err, data) {
if(err) {
return callback(err);
}
callback(null, data);
});
}
module.exports = {
query: query
}
Response
{"message":""}
Please change the bcrypt.compare code to following code. It is a callback function:
bcrypt.compare('123456', data.u_password, function(err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message:message,
});
})
EDIT 1: Please update the method to following logic:
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
if (err) {
throw err;
}
if (data && data.length > 0) {
var message = '';
if (data.u_password) {
bcrypt.compare('123456', data.u_password, function (err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message: message,
});
})
}
res.status(200).json({
message: "User Not found."
});
}
res.status(200).json({
message: "User Not found."
});
});
In my server.js under signup route after registering the user I want to send a verification email and a verification sms. But the smsService request trows an error. I am not sure what's wrong.
Can you help me to spot the error?
server.js:
app.post('/signup-user', upload.single('avatar'), (req, res) => {
let sAvatarImagePath = req.file.path.split("public/").pop()
let token = jwt.sign({
username: req.body.email,
}, 'supersecret', {
expiresIn: 240
});
user.createUser(req.body, sAvatarImagePath, (err, jResult) => {
if (err) {
return res.send(jResult)
}
mailer.sendEmail(res, req.body, token)
smsService.sendSms(req, res, (err, jResult) => {
if (err) {
return res.send(jResult)
}
})
return
})
})
smsService.js:
var smsService = {}
smsService.sendSms = (req, res, fCallback) => {
const sUrl = 'http://smses.io/api-send-sms.php';
const sToken = '$2y$10$//Qx9DsrDCIeNeWIjr1V.uWRR3m9raVGJNN4iDRZsxNDxknvCJsPC';
let sRecipientNbr = req.body.mobile_number;
let sMessage = '5678'
console.log('CALLING SMS API...', sRecipientNbr);
req.post(
sUrl, {
form: {
action: 'SEND',
mobile: sRecipientNbr,
message: sMessage,
apiToken: sToken,
},
},
(err, res, body) => {
if (err) {
console.log('ERROR WHEN CALLING SMS API', err);
return fCallback({
error: true,
message: 'System is currently unavailable'
});
}
var jResponse = safeJsonParse(body);
console.log('SMS API return:', jResponse);
if (jResponse.status != 'ok') {
console.error('SMS API RETURNED ERROR', err, jResponse);
return fCallback({
error: true,
message: 'System is currently unavailable'
});
}
return fCallback(false);
},
);
}
module.exports = smsService
I think you are confused between express Request object and NodeJS request module. You need to install NodeJS request module to make external http request
npm install request --save
and then use in service smsService.js
var request = require('request');
var smsService = {}
smsService.sendSms = (req, res, fCallback) => {
const sUrl = 'http://smses.io/api-send-sms.php';
const sToken = '$2y$10$//Qx9DsrDCIeNeWIjr1V.uWRR3m9raVGJNN4iDRZsxNDxknvCJsPC';
let sRecipientNbr = req.body.mobile_number;
let sMessage = '5678'
console.log('CALLING SMS API...', sRecipientNbr);
request.post(
sUrl, {
form: {
action: 'SEND',
mobile: sRecipientNbr,
message: sMessage,
apiToken: sToken,
},
},
(err, res, body) => {
if (err) {
console.log('ERROR WHEN CALLING SMS API', err);
return fCallback({
error: true,
message: 'System is currently unavailable'
});
}
var jResponse = safeJsonParse(body);
console.log('SMS API return:', jResponse);
if (jResponse.status != 'ok') {
console.error('SMS API RETURNED ERROR', err, jResponse);
return fCallback({
error: true,
message: 'System is currently unavailable'
});
}
return fCallback(false);
},
);
}
module.exports = smsService
I hope this will help you
I am not sure where i went wrong,when i run the code,it says error res.json(res) is not a function......
my node.js,
exports.inserttopic = function (req, res) {
var topics = new Topics(req.body);console.log(topics)
topics.status = '1';
topics.type = 'topics';
var data = {};
topics.save(function (err, res) {
if (err) {
console.log(err);
return err;
}
data = { status: false, error_code: 1, message: 'Unable to insert' };
if (res) {
data = { status: true, error_code: 0, result: res, message: 'Inserted successfully' };
}
res.json(data);
});
};
Use a different variable name when you do topics.save() than res. In your code, you are overwriting the original res and thus do not have access to the response object.
So this is what your code would look like
exports.inserttopic = function (req, res) {
var topics = new Topics(req.body);console.log(topics)
topics.status = '1';
topics.type = 'topics';
var data = {};
topics.save(function (err, mongooseResponse) { \\ Do not use res here
if (err) {
console.log(err);
return err;
}
data = { status: false, error_code: 1, message: 'Unable to insert' };
if (mongooseResponse) {
data = { status: true, error_code: 0, result: mongooseResponse, message: 'Inserted successfully' };
}
res.json(data);
});
};
hello i'm trying to GET a book by his name from my db but when i execute the script the localhost shuts down and i have to restart. also i get the error :
ReferenceError: text is not defined
here is the server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
//display a specific product stored in database
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
Products.find(Products, req.param('name'), function(Products) {
if (!text) res.status(500).send("server error");
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
and the database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection('text').save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection('text').findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
What am i doing wrong?
not sure if there are other issues with the code. but with the error ReferenceError: text is not defined, might the compiler be complaining that they cannot determine where text was declared in the following lines?
apiRoutes.get('/book/:title', function (req, res) {
...
if (!text) res.status(500).send("Server error");
...
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
...
if (!text) res.status(500).send("server error");
...
if that is the error, you might need to replace text with req.body.text
I am trying to update the value of my model and it does not work.
The weird thing is that I am printing out the result and it looks different than what I see in my database by using Robomongo.
Any thoughts why this happens?
Here is my code:
exports.create = function(req, res) {
var productId = req.query.product;
if (productId) {
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price =! 0 )
request.status = 'ready';
console.log(request);
(Here I see in the terminal: status = ready)
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});
} else {
var pages = require('../../schemas/wizard/request')();
res.render('requests/form', {
title: 'Make a Request',
pages: pages,
saveState: false
});
}
};
When I am checking the database status is still on pending.
You're changing the status property, but you're not saving the document back to the database after doing so:
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price !== 0) {
request.status = 'ready';
request.save(function(err) { // <-- save it back to the database
if (err) {
console.log('oh no! error', err);
} else {
console.log(request);
}
});
}
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});