Running an express server on a machine - express

I have a machine to which I can SSH. I have installed the express and other relevant node_modules. I have written a basic server code for "Hello World".
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sed("Hello World!");
});
app.listen(8XXX, "172.XX.XXX.XXX");
However, i get the following error.
Error: listen EADDRNOTAVAIL 172.28.120.107:5559
I have already sshed to my mahcine. Should i be giving the IP address as "127.0.0.1" in the server code.
Very new to this . Thanks

Related

Looking for a better way to authenticate Google Cloud Function with a service account. Right now I'm storing the credentials json file on the backend

I'm looking for a better way to authenticate Google Cloud Function with a service account. Right now I'm storing the credentials json file on the backend. This is the code for my app https://github.com/ChristianOConnor/spheron-react-api-stack. This app could be deployed on any hosting platform, but at the moment the app is built to deploy on a Web3 protocol called Spheron. TLDR, Spheron runs the backend express server on a web3 friendly content serving/hosting platform called Akash. This means that whoever is hosting my backend express server has access to my GCP service account's credentials. You can see all of the code in the link I provided but just for ease of access this is the server.js file which will be on Akash.
server.js
var express = require("express");
var app = express();
require("dotenv").config();
const GoogleAuth = require("google-auth-library").GoogleAuth;
const cors = require("cors");
app.use(
cors({ origin: process.env.ORIGIN, credentials: process.env.CREDENTIALS })
);
app.get("/hello", async function (req, res) {
const keyInJsn = JSON.parse(process.env.CREDENTIALS_STR);
const auth = new GoogleAuth({
credentials: keyInJsn,
});
const url = process.env.RUN_APP_URL;
//Create your client with an Identity token.
const client = await auth.getIdTokenClient(url);
const result = await client.request({ url });
const resData = result.data;
res.send(resData);
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://localhost:", port);
});
process.env.CREDENTIALS_STR is the service account credentials set up in this format:
CREDENTIALS_STR={"type": "service_account","project_id": "<PROJECT ID>","private_key_id": "<PRIVATE KEY ID>","private_key": "-----BEGIN PRIVATE KEY-----\<PRIVATE KEY>\n-----END PRIVATE KEY-----\n","client_email": "<SERVICE ACCOUNT NAME>#<PROJECT NAME>.iam.gserviceaccount.com","client_id": "<CLIENT ID>","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/<SERVICE ACCOUNT NAME>.iam.gserviceaccount.com"}
The Akash provider can see this string. Is there a better way to do authentication for a GCP service account that doesn't expose the credntials to a hosting/server provider?
Also don't be throw off by the web3 stuff. This app essentially works the same as a traditional web2 app with a backend and a client. If it helps you to think about it different, picture that I'm deploying on Netlify with a static client and a Netlify Function.
The compromise I came to was creating an API Gateway for the function. This allows the function to be called without any credentials and still run from a service account. It creates a separate quasi-vulnerability though, as anyone with the API Gateway link can also call the function unauthenticated.
First, I enabled Service Management APIs, API Gateway API, and Service Control API. Then I made an API Gateway with my service account that runs my referenced cloud function. I uploaded a file like this for the api spec:
swagger: '2.0'
info:
title: api-gateway-cloud-function
description: API Gateway Calling Cloud Function
version: 1.0.0
schemes:
- https
produces:
- application/json
paths:
/whateveryouwanttocallthispath:
get:
summary: My Cloud Function
operationId: whatever
x-google-backend:
address: <CLOUD_RUN_URL>
responses:
'200':
description: OK
You can test it by running the function via curl command in a bash terminal curl {gatewayId}-{hash}.{region_code}.gateway.dev/v1/whateveryouwanttocallthispath. It works with no credential json file.
The problem is that you could achieve a similar result by just allowing the function to be called unauthenticated... Idk if this method has many benefits.

Vue mqtt throws an error as ws does not work in the browser

I am really new to vue and for this project I am trying to connect my code with MQTT HOST URL ws://21.17.0.1:9009/. When I use the same code and run on local laptop as from XAMP LOCALHOST, it works fine without any error. When I push the code to my company server and try to run the same code then it throws me an error as ws does not work in the browser. Browser clients must use the native WebSocket object. Is it because I am defining ws url inside mqtt.connect?
SCRIPT
runMqtt() {
var mqtt = require('mqtt');
var client = mqtt.connect('ws://21.17.0.1:9009/');
}
client.on('connect', function () {
client.subscribe('route_status', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
var message = {command: "tap", route_status: "TRUE"};
var obj = JSON.stringify(message);
client.publish('server_commands', obj, {qos: 1});
Not sure if the mqtt.js code supports WebSockets in a brower (as your error message states.) You might want to try Steve's tutorial: http://www.steves-internet-guide.com/using-javascript-mqtt-client-websockets/ ...which uses a different library to do ws from a browser. Or... just try a different method like 'mqtt://' or 'tcp://'

Heroku SSL redirect for MEAN app

I have a MEAN app on Heroku. I want to ensure all traffic is going via HTTPS.
I have tried two npm modules
https://www.npmjs.com/package/express-sslify and
https://www.npmjs.com/package/heroku-ssl-redirect
In my app.js file I did the following
var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();
// enable ssl redirect
app.use(sslRedirect());
this is then used in www file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('node-rest:server');
var http = require('http');
var sslRedirect = require('heroku-ssl-redirect');
var enforce = require('express-sslify');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
I can't seem to get the app to redirect and thus if people use the url with https it servers them a warning
You need to enforce SSL before the express.static
app.use(express.static(path.join(__dirname, 'public')));
and then it works great

CRUD operations using DynamoDB with expressjs (node js)

I am trying to create a route which will perform some CRUD operations on DynamoDB.
At high level , it can be understood as :
The node js server application is running .(i.e. command 'node server.js' is being triggered)
The user uses POSTMAN of chrome browser to do route requests.
The user does a GET request for 'http://localhost:8080/listtablesofdynamodb'.
The specific route connected with this url gets hit which should do dynamodb specific activity. (like connecting to dynamodb ,fetching table names and showing it in callback method.)
the reason I am asking this question is because I could not find any relevant tutorial of how to do dynamodb activity by using express js of node. All I could find is console applications on aws website which seems not useful for me.
Any kind of help is highly appreciated.
Access key required
All you need to d is make a DynamoDB object to connect too
var ddb = require('dynamodb').ddb({ accessKeyId: '< your_access_key_id >', secretAccessKey: '< your_secret_access_key >' });
put this under your require statements, turn on your server. Then you can just fill out the routes to do the CRUD operations you need.
To test it use
ddb.listTables({}, function(err, res) {console.log(res);});
This will list all the tables in your db.
for full source check here
Best of luck
fortunately, I could manage to use aws-sdk in my route. the solution have two stages:
Run the code in your aws account's EC2 instance and attach an IAM role which allows the ec2 instance to talk to dynamodb. (in this way you don't need to hard-code access key in your code) see this article.
can take reference of the below code for initial code scaffolding.
`
var express = require('express');
var router = express.Router();
var AWS = require("aws-sdk");
AWS.config.update({
region: "us-west-2",
endpoint: "dynamodb endpoint specific to your aws account"
});
var dynamodb = new AWS.DynamoDB();
var params = {
ExclusiveStartTableName: "stringvalue",
Limit: 10
};
/* GET users listing. */
router.get('/', function (req, res) {
console.log("entered into dynadb route");
dynamodb.listTables(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
res.send(data);
}
});
});
module.exports = router;
`

Creating a expressjs proxy server between webpack and API

Hello i'm creating a web application using webpack, which makes REST api call to a backend server. The problem I have is CORS issues, so I will need to use a proxy.
Which leads me to how do I connect wepback-dev-server which runs on port(8080) to my api server which runs on port (7000)? Would my proxy server run same as port(8080)?
I read up on expressjs, npm node-http-proxy and webpack, but struggling to tie it all together.
I'm new to proxying.
Below a sample config for webpack-dev-server, see the proxy option
var config = {
// webpack stuff here ...
//dev server configuration
devServer: {
// ...
// every request made to 'locahost:8080/api/xxxx' will be proxyfied to 'http://localhost:7000/api/xxxx'
proxy: {
"/api/*": {
target: "http://localhost:7000",
secure: false,
rewrite: function(req, options) {
//you can handle rewrite here if you need to
}
},
}
},
//
};
module.exports = config;
As described here https://webpack.github.io/docs/webpack-dev-server.html#proxy
Hope it helps,
EDIT as for webpack-dev-server v 1.14.1 'rewrite' is still implemented