Following is code I am using to connect Slack with Salesforce to fetch usreInfo.
Everything works fine until I call 'whoami' function. I am receiving a JSON file from salesforce with access token and other details.
I am trying to put that JSON file inside mappings object and fetch the values inside it in the 'whoami' function.
access_token: '00D2x000001eSKboj9MZ_C1cMLV5N823jCiHXl.9WAu2gRQJQ_mtkbGWj3Yd.GvCWncFMYTuMd4AROItvGW6unk8fsxqO',
signature: '7DGROVVQDt0fqubf6zQdTXSDtFPEezeVsyDk0kg=',
scope: 'full',
id_token: 'eyJraWQiOiIyMjIiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoianJZeVc3RUVkZ0VOQ3pramNHdVBPQSIsInN1YiI6Imh0dHBzOi8vbG9naW4uc2FsZXNmb3JjZS5jb20vaWQvMDBEMngwMDAwMDFlU0tiRUFNLzAwNTJ4MDAwMDAxNlpsREFBVSIsImF1ZCI6IjNNVkc5N3F1QW1GWkpmVnk5JsOFF3aldtck5ZTEJYMzdoenExWXpJcDNEZFNHbVc2YzZiaHc0b3BpSVdQRFVzMVMiLCJpc3MiOiJodHRwczovL2xvZ2luLnNhbGVzZm9yY2UuY29tIiwiZXhwIjoxNTg4MTQzMjMwLCJpYXQiOjE1ODgxNDMxMTB9.WY9ELT5c65p8UeZ3yPRX-Ph8cc-Z2tprY1lCEv1KVos5XfO6qUNQQ_JmTACb-n6fHH3rWZgnceBMD6qlnXeIFvtmVg_MX3oXzfQKmkuo0x0HTp7mSempxcN6vsPIixoOGkOH-v712G3V36t_TU6ZcMn-Pc0xpSKDgEeFL7egqypiNoqXcm_wd_2tNUeLXwiYml80q7MI6SvHn2XVY0xfh6C5ffl2G4bCc8dckEscERa6edeuIrLA4R1x5v4djdK4X2D_TKTTpI4mX_YzuGkZVPaUsgcuk5jMqo2nF8tL37vOvKHI6qlXBUnlUXeJbh6PlfZi7CHi-uwweJQCmOq_69GwThisFHSvuSh9hreVGUmlFDb79qLnAGe5Y5Nm50h-ec6N2v7CN8pjg54tVHe-WfsKKLELkwLe24ZNZTEMLvHGye8iYXkyb-7sRNC9YKYSK_Ubcwev44JlmaShw4NO0GLqgYz5a_1x_Kz6Uc3MdJd7IsmF1AbgNLppmb09wA6s3_Ov871FmdKe8dAFgIr1xJ7LNZHmzNd1b3kHgGleMA8NAwn1GCZV9ItR1vWxZ24X6tZpICTu6pTQVT9PRHJ17zK6RcNfIuW9yXfM-xO2z7nBu1E2zBtm7ulPNSemUY9edeD5Nf1mnsNtTGiOMHkcMoaIHryrkbZ5YTGPJmlBm3c',
instance_url: 'https://ap17.salesforce.com',
id: 'https://login.salesforce.com/id/00D2x00000SKbEAM/0050000016ZlDAAU',
token_type: 'Bearer',
issued_at: '1588143490'
}
Above is the access token string i am receiving from the salesforce.
var express = require('express');
var request = require('request');
var url = require('url');
var clientId = 'hidde ';
var clientSecret = 'hidden';
var SF_LOGIN_URL = "https://login.salesforce.com";
var SF_CLIENT_ID = "hidden";
var SF_CLIENT_SECRET = "hidden";
var SF_AUTH_CODE;
var SF_ACCESS_TOKEN;
var SF_ACCESS_TOKEN_1;
var SF_DOMAIN;
var slackUserId;
var mappings = {};
// We define the port we want to listen to. Logically this has to be the same port than we specified on ngrok.
const PORT=4390;
// Instantiates Express and assigns our app variable to it
var app = express();
app.enable('trust proxy');
//var server = http.createServer(app);
//Lets start our server
app.listen(PORT, function () {
//Callback triggered when server is successfully listening.
console.log("Example app listening on port " + PORT);
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// Route the endpoint that our slash command will point to and send back a simple response to indicate that ngrok is working
app.post('/oauth', function(req, res) {
oauth(req, res);
slackUserId = req.body.user_id;
});
app.get('/oauth', function(req, res) {
// console.log(req.query.state);
oauth_access(req, res);
SF_AUTH_CODE = req.query.code;
});
app.post('/whoami', function(req, res){
console.log("Inside whoami");
if(slackUserId === req.body.user_id){
console.log("Crossed user ID");
userInfo();
res.send(req);
}
});
function oauth(req, res){
res.redirect(200, `${SF_LOGIN_URL}/services/oauth2/authorize?response_type=code&client_id=${SF_CLIENT_ID}&redirect_uri=https://hidden.ngrok.io/oauth&display=touch}`);
}
function oauth_access(req, res){
res.redirect(200, `${SF_LOGIN_URL}/services/oauth2/authorize?response_type=code&client_id=${SF_CLIENT_ID}&redirect_uri=https://hidden.ngrok.io/oauth&display=touch}`);
}
function oauth_access(req, res){
let options = {
url: `${SF_LOGIN_URL}/services/oauth2/token`,
qs: {
grant_type: "authorization_code",
code: req.query.code,
client_id: SF_CLIENT_ID,
client_secret: SF_CLIENT_SECRET,
redirect_uri: `https://hidden.ngrok.io/oauth`
}
};
request.get(options, function (error, response, body) {
if (error) {
console.log(error);
return res.send("error");
}
//Storing the body consisting of access token to the mappings
// SF_ACCESS_TOKEN = mappings[slackUserId].access_token;
//Accessing the access token supplied by the SF
// console.log(mappings[slackUserId].access_token);
let html = `
<html>
<body style="text-align:center;padding-top:100px">
<img src="/images/linked.png"/>
<div style="font-family:'Helvetica Neue';font-weight:300;color:#444">
<h2 style="font-weight: normal">Authentication completed</h2>
Your Slack User Id is now linked to your Salesforce User Id.<br/>
You can now go back to Slack and execute authenticated Salesforce commands.
</h2>
</body>
</html>
`;
res.send(html);
//body is in JSON format so we will try to store it inside global JSON object and access it through out the script!
// slackUserId_value = slackUserId.toString();
// console.log(slackUserId_value);
console.log(typeof(body));
// mappings[slackUserId].body = undefined;
mappings[slackUserId] = JSON.parse(body);
console.log(typeof(mappings));
console.log(mappings[slackUserId]);
// console.log(mappings);
// access_token_string = "access_token";
// console.log(mappings[slackUserId]);
console.log(mappings[slackUserId].access_token);
SF_ACCESS_TOKEN = mappings[slackUserId].access_token;
//SF_ACCESS_TOKEN_1 = SF_ACCESS_TOKEN;
});
};
function userInfo(){
console.log("User Info Function");
// SF_ACCESS_TOKEN = mappings[slackUserId].access_token;
mappings[slackUserId].access_token = undefined;
//console.log(mappings[slackUserId].access_token);
let options = {
url: `https://login.salesforce.com/services/oauth2/userinfo`,
qs: {
oauth_token: SF_ACCESS_TOKEN,
redirect_uri: `https://hidden.ngrok.io/whoami`
}
};
request.post(options, function(error, response, body){
if(error){
console.log(error);
return res.send("error");
}
});
};
Following is the output:
string
object
{
access_token: '00D2x000001eSKb!ARwAv1AWvtCd1.xew2dqgscgNfryydnpPlWbTrC7eQEw0ViEb1v7SWbwcMDHOHiyWQ6a0y9DFJ56.ldKDGfoG',
signature: 'lXynNIOCEF6Qz5m4qsG8dCfucwNmEkx5YeEKRH0=',
scope: 'full',
id_token: 'eyJraWQiOiIyMjIiLCJ0eXAiOiciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiR1dPdi0xTzJnZl91WnFidkFVOEtYZyIsInN1YiI6Imh0dHBzOi8vbG9naW4uc2FsZXNmb3JjZS5jb20vaWQvMDBEMngwMDAwMDFlU0tiRUFNLzAwNTJ4MDAwMDAxNlpsREFBVSIsImF1ZCI6IjNNVkc5N3F1QW1GWkpmVnk5Mjk5MEgxaS5uaW1nRkRyREZockJsOFF3aldtck5ZTEJYMzdoenExWXpJcDNEZFNHbVc2YzZiaHc0b3BpSVdQRFVzMVMiLCJpc3MiOiJodHRwczovL2xvZ2luLnNhbGVzZm9yY2UuY29tIiwiZXhwIjoxNTg4MTQzNzEyLCJpYXQiOjE1ODgxNDM1OTJ9.aI-wxVy2KLo9GDQDjxffdaZv8BmdftUQkWtI8kpXby8h-iLvNRDLSY4KrDQwJgAQAB2HUUaabftc2u-FeLh99h5Zuu4SGiyGZVPsPZ0Fkf0SjAcLiR4Q9caaYCwvlCkK_PM_v0IqWO413kXkcw2wEqvko-ekOM0bss26Qpiti0pcJntcMBn7XyIiAHhA7Fx5AhF9VnNyJIbI9cIIOFHtY_CoQsBgl-HmM7aYY5zXCUSdjbm4a4hNzV1veE4DL5Oxp5gto3vhRLd198koIaDA3xaIf_nyal6PEcafHfdQ3QlrNnSpigrKkB5Y5-vwY1xLf0EwkQ2bcOzT7l7fPsV1CN4PY3vjUyj1_tgpR_RJMTApM2etTbB1nMFxwTAnTwctVuZfK5fZeTp04XlZOpAyysAUaS9_1uhb6fLn-8CHW3tcPTT0cMqmJ0OgB5Tio_TGNRHb-xbWXxkFHXuatX2Lwj94xo_RfbT4CPYfK9JGQvsyPy8clclwsn-KLW8lx7tYYl2pEQthz9UX14WmgAQ2PzrVgEcTvf-kG4oORZsBvNraBcZVrYSdGUxaicjfoYA3Ue1sXIhyW_TvvRqsgWcXzhO-Qz2DuT6TTxb0tC6zlfvjeShhvnlLcukUfeyZPbuSksALD-ApLEQwAx8AzKZlmQ6N0dj7-CDcmGoG_4f493k',
instance_url: 'https://ap17.salesforce.com',
id: 'https://login.salesforce.com/id/00D2x01eSKbEAM/0052x0000lDAAU',
token_type: 'Bearer',
issued_at: '15881435266'
}
00D2x000001eSKb!ARwAQMguUkqgscgNfryydnpPlWbTrC7eQEw0ViEb1v7SWbwcMDHOHiyWQ6a0y9DFJ56.ldKDGfoG
Inside whoami
Crossed user ID
User Info Function
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle
at JSON.stringify (<anonymous>)
at stringify (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/response.js:1123:12)
at ServerResponse.json (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/response.js:260:14)
at ServerResponse.send (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/response.js:158:21)
at /Users/sonagrasumit/Desktop/salckapp/index.js:51:17
at Layer.handle [as handle_request] (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/router/layer.js:95:5)
at /Users/sonagrasumit/Desktop/salckapp/node_modules/express/lib/router/index.js:281:22
I have modified credentials for security reasons.
Related
I start learning Node.js and Express.js and I'm trying to create a simple API to list data from JSON file (using the GET method) and add a new user using the POST method.
the GET method works fine but the POST method does not work
when I request http://127.0.0.1:8080/listusers the API sends all users in a JSON file.
when I request http://127.0.0.1:8080/adduser the API has to add new User Info and send the new data back to the browser.
NOTE: I read all the questions on Stackoverflow about this problem but
non of them help me so I have to ask again.
the problem is when I request http://127.0.0.1:8080/adduser I get the following error
Cannot GET /adduser
here is the server.js:
var express = require('express');
var app = express();
var fs = require('fs');
var user = {
"user4" : {
"name" : "mounir",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
};
app.post('/adduser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end(JSON.stringify(data) );
});
});
app.get('/listusers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("listening at http://%s:%s", "0.0.0.0", port)
});
The answer is in the error. Cannot GET /adduser. Keyword GET! If you are making a post request, be sure you include the appropriate headers and that you are making a POST request, with a body, and not a GET request. For instance if you are using fetch:
const myInit = {
method: 'POST',
headers: myHeaders,
body: {
...
}
};
fetch("http://127.0.0.1:8080/adduser", myInit)
.then(res => {
...
});
I am troubling with nodejs proxy server modified(write) response.
I want to achieve auto login for one site via node proxy server and for that i have to query in database then i can modified response but it seems req ended before req.write and getting Error: write after end
Below is my implementation so far.
var express = require('express');
var proxy = require('http-proxy-middleware');
var options = {
target: 'http://example.com/', // target host
changeOrigin: true,
onProxyReq: function onProxyReq(proxyReq, req, res) {
var _write = res.write;
var body = "";
proxyReq.on('data', function(data) {
data = data.toString('utf-8');
body += data;
});
res.write = function (data) {
try{
//I have database query here instead of setTimeout
setTimeout(function(){
/* Modified response here and write */
_write.call(res, data); //can't write because req already end
},3000);
} catch (err) {
console.log('err',err);
}
}
}
}
// create the proxy (without context)
var exampleProxy = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use('/', exampleProxy);
app.listen(8080);
Can anyone guide me how to achieve this ?
Introduction
I have a three functions, each one would feed data into then next. The objective is first to retrieve data then authenticate a API key then finally using the generated API key and data retrieve from the first function post to the API in the third function.
Order
First function function to retrieve data from a post.
Second function gets API key requested from a API.
Third function posts data to the API.
Needed functionality
I need the variables retried in the first function and the API key generated in the second function to be available for use in the third function.
Problems and questions
emailUser is not being found to use in the third function
api_key is not being found in the third function
also the functions need to run in order first, second then third
This all works if I was to insert the data manual but when input the variables it dose not work, I understand that it is because the variables being within the function but how do I fix this, also how do I set the order of the functions ?
Full code
// Grab the packages needs and sets server
//---------------------------------- Grab the packages we need and set variables --------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 8080;
// Varibles to use in second and third function
var password = 'password';
var userkey = '6767712';
var emailAdmin = 'admin#admin.com';
// start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Server started! At http://localhost:' + port);
// First Retrieve posted data from Front-End
//---------------------------------- Retrieve posted data from Front-End -----------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------
// POST http://localhost:8080/api/index
app.post('/api/data', function (req, res) {
console.log(req.body);
var Fname = req.body.fname;
var Lname = req.body.lname;
var emailUser = req.body.email;
res.send(Fname + ' ' + Lname + ' ' + emailUser);
});
app.get('/', function (req, res) {
res.send('hello world, Nothing to see here...');
});
// Second Get Posted variables
//---------------------------------- Now authenticate the api and get api_key -----------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
// turn off when live
DEBUG: true
}, function (err, client) {
if (err) {
// Authentication failed
// handle error
console.error("Authentication Failed", err)
} else {
// Authentication successful
// gets api key
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
}
});
// Third Retrieve posted data from Front-End
//---------------------------------- Send all data to API -----------------------------------------------------
// ------------------------------------------------------------------------------------------------------------
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/create/email',
method: 'POST',
headers: headers,
form: {
'email': emailUser,
'user_key': userkey,
'api_key': api_key
}
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log("error",body)
}
else {
console.log("Sent Data",body);
}
});
best way is using async package (install with npm install async) that is very famous and useful package in npm your functions will be something like this:
var async=require('async');
var handler = function (req,res) {
async.auto
(
{
getBody: function (cb, results) {
var body=req.body;
//prepare body here then send it to next function
cb(null, body)
},
getApi: ['getBody', function (results, cb) {
var preparedBody=results.getBody;
// get the api here and send it to next function
var apiKey=getApi()
cb(null, {apiKey:apiKey,preparedBody:preparedBody})
}],
third: ['getApi', function (results, cb) {
var preparedBody=results.getApi.preparedBody;
var apiKey=results.getApi.apiKey;
// now data are here
cb(null,true)
}]
},
function (err, allResult) {
// the result of executing all functions goes here
}
)
}
Another way to handle this problem is by allowing the express middleware flow to do those things for you on a separate Router.
I have setup a sample Glitch for your reference using stand in functions to simulate network calls HERE.
In your case, you would have to do something like:
//API route
var express = require('express');
var router = express.Router();
router.post('/data', function (req, res, next) {
console.log(req.body);
req.bundledData = {};
req.bundledData.fname = req.body.fname;
req.bundledData.lname = req.body.lname;
req.bundledData.emailUser = req.body.email;
next();
});
router.use(function(req, res, next){
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
// turn off when live
DEBUG: true
}, function (err, client) {
if (err) {
// Authentication failed
// handle error
console.error("Authentication Failed", err)
} else {
// Authentication successful
// gets api key
req.bundledData.api_key = client.apiKey;
console.log("Authentication successful !", api_key);
next();
}
});
});
router.use(function(req, res, next){
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/create/email',
method: 'POST',
headers: headers,
form: {
'email': emailUser,
'user_key': userkey,
'api_key': api_key
}
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log("error",body)
}
else {
console.log("Sent Data",body);
//Processing is complete
res.json({
success:true,
body:body
});
}
});
});
I want to trigger my bot with http request (for example just entering http://localhost:3978/api/messages/http) so after triggering it, it will send every user that is connected to this bot some message.
I have seen this topic: How to send message later in bot framework?
And this is what I have so far:
var restify = require('restify');
var builder = require('botbuilder');
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
var bot = new builder.UniversalBot(connector);
bot.dialog('/',function (session) {
var reply = session.message; // address: reply.address
reply.text = 'Wake up!'
console.log(reply.text);
bot.send(reply);
});
// Create response function
function respond(req, res, next) {
res.send('hello ' + req.params.name);
bot.send(reply);
next();
}
server.get('/api/messages/:name', respond);
Unfortunately, it doesn't send any messages while I am acessing my http://localhost:3978/api/messages/http. I also tried to use
connector.send('message');
But it always throughs me "ERROR: ChatConnector: send - message is missing address or serviceUrl."
UPDATE:
I have announced a global var for the reply with
var globalreply;
bot.dialog('/',function (session) {
globalreply = session.message; // address: reply.address
globalreply.text = 'Wake up!'
console.log(globalreply.text);
bot.send(globalreply);
});
// Create response function
function respond(req, res, next) {
res.send('hello ' + req.params.name);
bot.beginDialog;
bot.send(globalreply);
next();
}
But now it throughs me an error:
TypeError: Cannot read property 'conversation' of undefined.
At my bot.send(globalreply); line.
Looking forward your help.
Best regards.
If you want to set up a normal HTTP API route, I suggest using the Restify API style routing, rather than the bot's /api/messages route handler.
For example:
function apiResponseHandler(req, res, next) {
// trigger botbuilder actions/dialogs here
next();
}
server.get('/hello/:name', apiResponseHandler);
I am trying to get a https loopback server up and running protected by OAuth. I am using the loopback gateway sample project as a reference. But for some reason I can't get the OAuth piece to work. What I mean is, even after adding in the OAuth bits and pieces, the APIs don't seem to be protected. I get a response back even if there is no token in my request. This is what my server.js looks like
var loopback = require('loopback');
var boot = require('loopback-boot');
var https = require('https');
var path = require('path');
var httpsRedirect = require('./middleware/https-redirect');
var site = require('./site');
var sslConfig = require('./ssl-config');
var options = {
key: sslConfig.privateKey,
cert: sslConfig.certificate
};
var app = module.exports = loopback();
// Set up the /favicon.ico
app.middleware('initial', loopback.favicon());
// request pre-processing middleware
app.middleware('initial', loopback.compress());
app.middleware('session', loopback.session({ saveUninitialized: true,
resave: true, secret: 'keyboard cat' }));
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
// Redirect http requests to https
var httpsPort = app.get('https-port');
app.middleware('routes', httpsRedirect({httpsPort: httpsPort}));
var oauth2 = require('loopback-component-oauth2')(
app, {
// Data source for oAuth2 metadata persistence
dataSource: app.dataSources.pg,
loginPage: '/login', // The login page url
loginPath: '/login' // The login processing url
});
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Set up login/logout forms
app.get('/login', site.loginForm);
app.get('/logout', site.logout);
app.get('/account', site.account);
app.get('/callback', site.callbackPage);
var auth = oauth2.authenticate({session: false, scope: 'demo'});
app.use(['/protected', '/api', '/me', '/_internal'], auth);
app.get('/me', function(req, res) {
// req.authInfo is set using the `info` argument supplied by
// `BearerStrategy`. It is typically used to indicate scope of the token,
// and used in access control checks. For illustrative purposes, this
// example simply returns the scope in the response.
res.json({ 'user_id': req.user.id, name: req.user.username,
accessToken: req.authInfo.accessToken });
});
signupTestUserAndApp();
//var rateLimiting = require('./middleware/rate-limiting');
//app.middleware('routes:after', rateLimiting({limit: 100, interval: 60000}));
//var proxy = require('./middleware/proxy');
//var proxyOptions = require('./middleware/proxy/config.json');
//app.middleware('routes:after', proxy(proxyOptions));
app.middleware('files',
loopback.static(path.join(__dirname, '../client/public')));
app.middleware('files', '/admin',
loopback.static(path.join(__dirname, '../client/admin')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.middleware('final', loopback.urlNotFound());
// The ultimate error handler.
app.middleware('final', loopback.errorHandler());
app.start = function(httpOnly) {
if(httpOnly === undefined) {
httpOnly = process.env.HTTP;
}
server = https.createServer(options, app);
server.listen(app.get('port'), function() {
var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' + app.get('port');
app.emit('started', baseUrl);
console.log('LoopBack server listening # %s%s', baseUrl, '/');
});
return server;};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
function signupTestUserAndApp() {
// Create a dummy user and client app
app.models.User.create({username: 'bob',
password: 'secret',
email: 'foo#bar.com'}, function(err, user) {
if (!err) {
console.log('User registered: username=%s password=%s',
user.username, 'secret');
}
// Hack to set the app id to a fixed value so that we don't have to change
// the client settings
app.models.Application.beforeSave = function(next) {
this.id = 123;
this.restApiKey = 'secret';
next();
};
app.models.Application.register(
user.username,
'demo-app',
{
publicKey: sslConfig.certificate
},
function(err, demo) {
if (err) {
console.error(err);
} else {
console.log('Client application registered: id=%s key=%s',
demo.id, demo.restApiKey);
}
}
);
});
}
I don't get any errors when the server starts up. Thoughts?
Got it figured. More information here https://github.com/strongloop/loopback-gateway/issues/17, but basically I had my rest-api middleware not configured right.