2 Way TLS node.js app to secure API

Not applicable

Exception on deploying app to apigee edge:

{"fault":{"faultstring":"Script node executed prematurely: Error: listen EINVAL\nError: listen EINVAL\n    at emit (events.js:72:0)\n    at net.js:1046:0\n    at _tickDomainCallback (trireme.js:491:0)\n    at _tickFromSpinner (trireme.js:422:0)\n","detail":{"errorcode":"scripts.node.runtime.ScriptExitedError"}}}

Code : I am able to start server in local but not in apigee edge.

var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var requestUrl = require('request');
var http = require('http');
var https = require('https');
var fs = require('fs');
const tls = require('tls');
var access=require('apigee-access');


var app = express();
var PORT = process.env.PORT || 443;
var sslOptions = {
    /*
    * Key & cert are backend server certificates It could be self signed
    */
    key: fs.readFileSync('./keys/backend-apigee-key.pem'),
    cert: fs.readFileSync('./keys/backend-apigee-cert.pem'),
    requestCert: true,
    /*
    * Download apigee enterprise certificate
    */
    ca: [ fs.readFileSync('./keys/client-apigee-enterpriseapigeecom-cert.crt') ]
  };
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
    secret: 'this-should-be-secure',
    resave: true,
    saveUninitialized: true,
    cookie: {}
}));
app.use(function (request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
app.get('/', function (request, response) {
    console.log('Request GET / default API!');
    response.send('Hello world');
});
app.get('/posts', function (request, response) {
    console.log('Request GET posts API!');
    var options = {
        uri: 'https://jsonplaceholder.typicode.com/posts',
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true
    };
    requestUrl.get(options, function (err, ds) {
        if (err) {
            response.send(err);
        } else {
            response.send(ds.body);
        }
    })
});
app.get('/posts/:postsId', function (request, response) {
    console.log('Request GET posts/postsId API!');
    var postsId = request.params.postsId;
    // console.log(postsId);
    requestUrl.get('https://jsonplaceholder.typicode.com/posts/' + postsId, function (error, postsresponse) {
        if (error) {
            response.send(error);
        } else {
            response.send(postsresponse.body);


        }
    });
});
app.post('/posts', function (request, response) {
    console.log('Request POST posts API!');
    var title = request.body.title;
    var comment = request.body.comment;
    var userId = request.body.userId;
    requestUrl.post('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: title,
            body: comment,
            userId: userId
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    }, function (err, ds) {
        if (err) {
            response.send(err);
        } else {
            response.send(ds.body);
        }
    })
});
// https.createServer(sslOptions,app).listen((9000),()=>{
//     console.log('The server is listening on port 9000');
// });
tls.createServer(sslOptions,app).listen((PORT),function(){
    console.log('The deployment mode on paigee is ' + access.getMode());
    console.log('The server is listening on port');
});

Please let me know if I am doing wrong.

Solved Solved
0 4 2,504
1 ACCEPTED SOLUTION

Not applicable

You will need uncomment your three lines and use `https` to listen for incoming requests and not use `tls`.

From the documentation: "All Node.js applications running in Apigee Edge must use the http or https module to listen for incoming requests. If you were to deploy a script that doesn't listen for incoming requests, it would simply execute and exit."

https://docs.apigee.com/api-platform/nodejs/understanding-edge-support-nodejs-modules#HTTPandHTTPS

View solution in original post

4 REPLIES 4

Not applicable

You will need uncomment your three lines and use `https` to listen for incoming requests and not use `tls`.

From the documentation: "All Node.js applications running in Apigee Edge must use the http or https module to listen for incoming requests. If you were to deploy a script that doesn't listen for incoming requests, it would simply execute and exit."

https://docs.apigee.com/api-platform/nodejs/understanding-edge-support-nodejs-modules#HTTPandHTTPS

I agreed. But as per apigee edge documents it asking to with tsl module :
https://docs.apigee.com/api-platform/system-administration/configuring-ssl-edge-backend-service#conf...

Please confirm,

Tushar - the doc you linked refers to HTTPTargetEndpoint.

You're not doing that. You're using a nodejs target. So that documentation is irrelevant.

2nd thing:

this answer is marked "Accepted". does that mean your question is resolved?

Thanks Dino.