I have a node.js app that has a few files that I am working with, but the main two javascript files are a RestController and AuthController. The RestController is supposed to call the AuthController to pull a new access token from Salesforce, the server that I am attempting to hit.
I currently set up my AuthController.js to work with promises so that I can wait to get my access token. The problem is I have no idea how to get my RestController.js file to wait for the access token from the AuthController.js file.
I am also very very new to Javascript and Promises, so I am not sure if I even set up my functions correctly. Basically, I want my AuthController to handle getting the access token and the RestController to handle the Rest request to our server.
AuthController.js
var fs = require('fs');
var jwt = require('jsonwebtoken');
var request = require('request');
var querystring = require('querystring');
var config = require('../../configs/config.json');
var filename = __dirname + '/../../' + config.key_path;
var access_token;
var readFilePromise = function(file) {
return new Promise(function(ok, notOk) {
fs.readFile(file, function(err,data) {
if (err) {
notOk(err);
} else {
ok(data);
}
});
});
}
var getAccessToken = function(key) {
return new Promise(function(ok,notOk) {
var jwtparams = {
iss : config.client_id,
sub: config.username,
aud: 'https://' + config.host,
exp : Date.now() + 300
};
var token = jwt.sign(jwtparams, key, {algorithm: 'RS256'});
var data = querystring.stringify({
grant_type : 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion : token
});
request.post({
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : data.length
},
url: 'https://' + config.host + '/services/oauth2/token',
body: data
}, function(error, response, body) {
if (error) {
return notOk(error);
}
try {
ok(JSON.parse(body).access_token);
} catch (e) {
notOk(e);
}
});
});
}
function main() {
readFilePromise(filename).then(function(data) {
getAccessToken(data.toString()).then(function(data) {
access_token = data.toString();
});
});
}
module.exports = {main};
RestController.js
var https = require('https');
var request = require('request');
var auth = require('./authController.js');
class SystemController {
doProcessPostStatus (req,res) {
if (!req.body.systemId) {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'System Id "systemId" variable is required.'
}
]);
} else if (typeof req.body.success === 'undefined') {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'Success "success" variable is required'
}
]);
} else if (!req.body.message) {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'Message "message" variable is required'
}
]);
}
var access_token = auth.main();
console.log(access_token);
}
}
var systemControllerVar = new SystemController();
module.exports = systemControllerVar;
Any help is greatly appreciated as I am currently stuck, thanks!
Related
I am trying to send a email with the help of O365. I have configured everything but I am getting a error
GraphError { statusCode: 405, code: 'Request_BadRequest',
message: 'Specified HTTP method is not allowed for the request
target.', requestId: '34f321-57de-4483-b97d-5957f8786ecb', date:
2019-09-16T00:17:53.000Z, body:
'{"code":"Request_BadRequest","message":"Specified HTTP method is not
allowed for the request
target.","innerError":{"request-id":"34f803b1-57de-4483-b97d-5957f8786ecb","date":"2019-09-16T05:47:51"}}'
}
Code
const APP_ID = "XXXXXXXXXXXXXXXXXX";
const APP_SECERET = "XXXXXXXXXXXXXX";
const TENANT_ID = "XXXXXXXXXXXXXXXX";
const TOKEN_ENDPOINT = "https://login.microsoftonline.com/XXXXXXXXXXXXXXXXXXXXX/oauth2/v2.0/token";
const MS_GRAPH_SCOPE = "https://graph.microsoft.com/.default";
const GRANT_TYPE = "client_credentials";
const graphScopes = ["User.Read", "Mail.Send"]; // An array of graph scopes
const request = require("request");
const endpoint = TOKEN_ENDPOINT;
const requestParams = {
grant_type: GRANT_TYPE,
client_id: APP_ID,
client_secret: APP_SECERET,
scope: MS_GRAPH_SCOPE
};
request.post({
url: endpoint,
form: requestParams
}, function(err, response, body) {
if (err) {
console.log("error");
} else {
// console.log(response);
// console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
// testGraphAPI(parsedBody.access_token);
let accessToken = parsedBody.access_token;
getMe(accessToken);
}
}
});
function getMe(accessToken) {
require("isomorphic-fetch");
const fs = require("fs");
const MicrosoftGraph = require("#microsoft/microsoft-graph-client").Client;
const options = {
defaultVersion: "v1.0",
debugLogging: true,
authProvider: (done) => {
done(null, accessToken);
},
};
// https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/samples/node/main.js
// https://learn.microsoft.com/en-us/graph/overview
const client = MicrosoftGraph.init(options);
// send an email
const sendMail = {
message: {
subject: "Test o365 api from node",
body: {
contentType: "Text",
content: "Testing api."
},
toRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}],
ccRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}]
},
saveToSentItems: "false"
};
client.api('/users/test1#abc.onmicrosoft.com ').post(sendMail).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
}
Can someone tell me where I am going wrong. Please help me out
I had the same error and it was a malformed url when sending to the users.
I think your url should be /users/test1#abc.onmicrosoft.com/sendMail
I am currently working with azure functions in javascript. In my function, I am first getting a specific element from my CosmoDB (this is the async/await part). I get a result and then I want to do an https POST request. However, my problem is, that it never finished the HTTPs request and I don't really know why. What am I doing wrong?
(As you can see I tried 2 different ways of doing the request, once with the standard https function and the commented out the part with npm request package. However, both ways won't work).
Here is my code:
const CosmosClient = require('#azure/cosmos').CosmosClient;
var https = require('https');
var http = require('http');
var request = require('request');
const endpoint = "someEndpoint";
const masterKey = "anymasterkey";
const database = {
"id": "Database"
};
const container = {
"id": "Container1"
};
const databaseId = database.id;
const containerId = container.id;
const client = new CosmosClient({
endpoint: endpoint,
auth: {
masterKey: masterKey
}
});
module.exports = function (context, req) {
const country = "de";
const bban = 12345678;
const querySpec = {
query: "SELECT * FROM Container1 f WHERE f.country = #country AND f.bban = #bban",
parameters: [{
name: "#country",
value: country
},
{
name: "#bban",
value: bban
}
]
};
getContainers(querySpec).then((results) => {
const result = results[0];
context.log('here before request');
var options = {
host: 'example.com',
port: '80',
path: '/test',
method: 'POST'
};
// Set up the request
var req = http.request(options, (res) => {
var body = "";
context.log('request');
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
context.res = body;
context.done();
});
}).on("error", (error) => {
context.log('error');
context.res = {
status: 500,
body: error
};
context.done();
});
req.end();
// request({
// baseUrl: 'someURL',
// port: 443,
// uri: 'someuri',
// method: 'POST',
// headers: {
// 'Content-Type': 'text/xml;charset=UTF-8',
// 'SOAPAction': 'someaction'
// },
// function (error, response, body) {
// context.log('inside request')
// if (error) {
// context.log('error', error);
// } else {
// context.log('response');
// }
// }
// })
})
};
async function getContainers(querySpec) {
const {container, database} = await init();
return new Promise(async (resolve, reject) => {
const {
result: results
} = await container.items.query(querySpec).toArray();
resolve(results);
})
}
async function init() {
const {
database
} = await client.databases.createIfNotExists({
id: databaseId
});
const {
container
} = await database.containers.createIfNotExists({
id: containerId
});
return {
database,
container
};
}
The last thing that happens is the print of "here before request". After that the function just does nothing until it timesout. So what am I doing wrong? Can't I just this combination of await/async and requests?
As commented you are not sending any data to the POST call. You need to have a req.write before the req.end
req.write(data);
req.end();
That is why the POST call is failing for you. After this fix, it should work
i know this question asked many time before but still i'm struggling to figure this out. i have a set of js files. first one is index.js
app.all('/backend/*/*', function(req, res){ // backend/product/getProduct
serviceType = req.params[0];
methodType = req.params[1];
exports.serviceType= serviceType;
exports.methodType= methodType;
main.checkService()
});
in here im extracting the params and call checkService method in main.js file
main.js
function checkService(){
switch(index.serviceType){
case 'product':
product.checkMethod();
break;
default :
console.log('no such service')
}
}
then it move to product.js file
function checkMethod(){
var methodName = index.methodType,
res = index.res,
req = index.req;
switch(methodName){
case 'samplePost':
var body = req.body;
proHan.samplePost(body,function(data,msg,status){
sendRes(data,msg,status);
});
break;
default :
console.log('no such method')
}
function sendRes(jsonObj,msg,status){
var resObj = {
status : status,
result : jsonObj,
message : msg
}
res.json(resObj);
}
first it moves to samplePost method in handler.js
once the http req finised executing, callback return the results and call sendRes method and send the json
function samplePost(jsonString,cb){
var res = config.setClient('nodeSample');
// jsonString = JSON.parse(jsonString);
res.byKeyField('name').sendPost(jsonString,function(data,msg,status){
cb(data,msg,status);
});
}
to send http req i written a common file. that is config.js
function setClient(_cls){
var client = new Client(url);
return client;
}
function parentClient(url){
this.postBody = {
"Object":{},
"Parameters":{
"KeyProperty":""
}
};
}
function paramChild(){
parentClient.apply( this, arguments );
this.byKeyField = function(_key){
this.postBody.Parameters.KeyProperty = _key;
return this;
}
}
function Client(url){
parentClient.apply( this, arguments );
this.sendPost = function(_body,cb){
_body = (_body) || {};
this.postBody.Object = _body;
var options = {
host : 'www.sample.com',
port : 3300,
path: '/somrthing',
headers: {
'securityToken' : '123'
}
};
options.method = "POST";
var req = http.request(options, function(response){
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
cb(JSON.parse('[]'),'success',200)
});
});
//This is the data we are posting, it needs to be a string or a buffer
req.on('error', function(response) {
cb(JSON.parse('[]'),response.errno,response.code)
});
req.write(JSON.stringify(this.postBody));
req.end();
}
}
paramChild.prototype = new parentClient();
Client.prototype = new paramChild();
when i send the first req its work but from then again the server crashes. it seems like i can't call res.end method again in a callback method. how can i fix this. thank you.
you can't call res.end two times. Here is a simple exemple to deal with callback with a basic node server.
const http = require('http');
const hostname = '127.0.0.1';
const port = 4242;
let something = true;
function callback(req, res) {
something = !something;
res.setHeader('Content-Type', 'text/plain');
res.end('Callback Hello World\n');
}
const server = http.createServer((req, res) => {
res.statusCode = 200;
if (something) {
callback(req, res);
} else {
something = !something;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I am working in MEAN STACK application and i want to set mail's parameters dynamic.
route.js
var Helper = require("../helper.js");
router
.route("/api/user/registration")
.POST(function (req, res) {
//after user insert send mail
Helper.sendCustomEmail(params, function (error, response) {
if (error) {
console.log("Mail : " + error);
res.json({"status": 0, "error": {"other": "Oops! something went wrong, please try again later"}});
} else {
console.log("Message sent");
res.json({status: 1, message: 'Thank you for registration. You will get verification email soon', token: res.locals.user.jwttoken});
}
});
});
Helper.js
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = params.fs.readFileSync(basePath + "emailHeader.html").toString();
//read footer email template
var footerHtml = params.fs.readFileSync(basePath + "emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: this.getSiteSetting("SMTP_HOST"),
secure: true,
auth: {
user: this.getSiteSetting("SMTP_USER"),
pass: this.getSiteSetting("SMTP_PSSSWORD")
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: this.getSiteSetting("SMTP_FROM"),
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
};
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function($keyword) {
if ($keyword !== undefined && $keyword !== null && $keyword !== "") {
SiteSetting.findOne({setting_key : $keyword},function(err,siteSetting){
if(err){
return null;
}else{
if(siteSetting !== null){
console.log(siteSetting.setting_value);
return siteSetting.setting_value;
}
}
});
}else{
return null;
}
};
dependencies
"express" => "version": "4.13.4",
"mongoose" => "version": "4.4.4",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
from the following code SiteSetting function console.log print properly but before return mail send error occur.
Please give me a proper guideline for this code.
This can be solved as bellow.
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailHeader.html").toString();
//read footer email template
var footerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
var host = null;
var user = null;
var pass = null;
var from = null;
this.getSiteSetting("SMTP_HOST", function(res) {
host = res;
setParams();
});
this.getSiteSetting("SMTP_USER", function(res) {
user = res;
setParams();
});
this.getSiteSetting("SMTP_PASS", function(res) {
pass = res;
setParams();
});
this.getSiteSetting("MAIL_FROM", function(res) {
from = res;
setParams();
});
var setParams = function() {
if (host !== null && user !== null && pass !== null && from !== null) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: host,
//port: 25,
//port: 465,
secure: true,
auth: {
user: user,
pass: pass
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: from,
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
}
};
}
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function(keyword, callback) {
if (keyword !== undefined && keyword !== null && keyword !== "") {
SiteSetting.findOne({ setting_key: keyword }, function(err, siteSetting) {
if (err) {
callback(null);
} else {
if (siteSetting !== null) {
//console.log(siteSetting.setting_value);
callback(siteSetting.setting_value);
}else{
callback(null);
}
}
});
} else {
callback(null);
}
};
I am tring to upload a file using angular $http method to node backend
I want to upload the form with additional form fields.
This is my code
var data = new FormData();
data.append('title', 'sometitle');
data.append('uploadedFile', $scope.uploadedFile);
FileService.upload(url, data, function(data, status) {
if(status===HTTP_OK) {
$scope.uploadSuccess = true;
$scope.showUploadProgressBar = false;
} else {
// error occured
console.log(data);
}
});
FileService
FileService.upload = function(url, data, callback) {
$http({
method : 'POST',
url : url,
data : data,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(function(data, status) {
callback(data, callback);
}).error(function(data, status) {
callback(data, status);
});
};
I am using node multiparty module for file upload. I am receiving the file correctly. But the field value for title is undefined.
I don't know why title value is undefined
Node.js backend file upload handler
var form;
if(options.uploads.tempDir) {
form = new multiparty.Form({uploadDir : options.root + '/' + options.uploads.tempDir});
} else {
form = new multiparty.Form();
}
form.on('file', function(name, receivedFile) {
var tmpPath = receivedFile.path,
fileName = receivedFile.originalFilename,
targetDirectory = uploadDirectory + '/' + req.params.id,
targetPath = targetDirectory + '/' + fileName,
file = {
filePath : targetPath,
tempPath : tmpPath,
fileName : fileName,
size : receivedFile.size
};
fileUploadStatus.file = file;
// move file
fse.move(tmpPath, targetPath, function(err) {
if(err) {
console.log('Error moving file [ ' + targetPath + ' ] ' + JSON.stringify(err));
}
});
});
form.on('error', function(err) {
fileUploadStatus.err = err;
req.fileUploadStatus = fileUploadStatus;
next();
});
form.on('close', function() {
req.fileUploadStatus = fileUploadStatus;
next();
});
form.on('field', function(name, value) {
console.log('field called');
console.log(name);
console.log(value);
req.body = req.body || {};
req.body[name] = value;
});
// ignoring parts. Implement any other logic here
form.on('part', function(part) {
var out = new stream.Writable();
out._write = function (chunk, encoding, done) {
done(); // Don't do anything with the data
};
part.pipe(out);
});
// parsing form
form.parse(req);