Local datacenter is not defined : cassandraDB and expressJS - express

I followed the instructions for connecting cassandraDB and expressJs (V4.16.1) here -> https://expressjs.com/en/guide/database-integration.html#cassandra
but I am having this error in the browser:
msg
name "ArgumentError"
info "Represents an error that is raised when one of the arguments provided to a method is not valid."
message "'localDataCenter' is not defined in Client options and also was not specified in constructor. At least one is required. Available DCs are: [datacenter1]"
code index.js
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');
var client = new cassandra.Client({ contactPoints:['localhost'] });
client.connect(function(err, result){
console.log('cassandra connection done');
});
var getAlllogs = 'SELECT * FROM logs.ourlogs';
/* GET home page. */
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
client.execute(getAlllogs,[], function(err, result){
if(err){
res.status(404).send({msg:err});
} else{
res.render('index', {
ourlogs: result.rows[0]
})
}
});
});
module.exports = router;
code index.jade
extends layout
block content
h1 all logs
ul
each ourlog, i in ourlogs
li #{ourlog.curTime}
cassandra info
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.6 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh>
what did I miss?

This is the answer :
var client = new cassandra.Client({ contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1', keyspace: 'yourkeyspacename' });
ExpressJS team should edit it on their website

Related

My Web app is being blocked by CORS policy even after installing CORS in my Express app

I have a flutter web app that I am running on localhost to debug, my web app posts data to my Firebase Cloud functions API which then sends data to Google Bigquery to create a table, although I have installed CORS already I keep getting this error in my browser below
Access to XMLHttpRequest at 'https://us-central1-denance-cbf3f.cloudfunctions.net/api/create_table' from origin 'http://localhost:55073' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
us-central1-denance-cbf3f.cloudfunctions.net/api/create_table:1 Failed to load resource: net::ERR_FAILED
errors.dart:202 Uncaught (in promise) Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 897:28 get current
packages/http/src/browser_client.dart 71:22 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1687:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 155:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 707:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 736:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 533:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1219:7 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37324:58 <fn>
at Object.createErrorWithStack (:55073/dart_sdk.js:5070)
at Object._rethrow (:55073/dart_sdk.js:37715)
at async._AsyncCallbackEntry.new.callback (:55073/dart_sdk.js:37711)
at Object._microtaskLoop (:55073/dart_sdk.js:37568)
at _startMicrotaskLoop (:55073/dart_sdk.js:37574)
at :55073/dart_sdk.js:33324
this is my code below
const functions = require("firebase-functions");
const express = require('express');
var cors = require('cors');
const { BigQuery } = require('#google-cloud/bigquery');
const bigquery = new BigQuery();
var app = express();
app.use(cors);
app.use(express.json());
exports.api = functions.https.onRequest(app);
app.post('/create_table', cors(dynamicCorsOptions), function (req, res,) {
'use strict';
async function createTable() {
let schema = [];
async function groupUp() {
for (let key in req.body) {
schema.push({ name: req.body[key]['name'], type: req.body[key]['type'] });
}
}
await groupUp();
await doingIt();
async function doingIt() {
var datasetId = 'denanse'; // Existing dataset
var tableId = 'hrhrhhh'; // Table to be created
const options = {
schema: schema,
location: 'US',
};
const [table] = await bigquery
.dataset(datasetId)
.createTable(tableId, options);
console.log(`Table ${table.id} created.`);
res.send(`Table ${table.id} created.`);
}
}
createTable();
});
how can I resolve this?
Currently your usage of the cors package is bugged in two ways. You only need to implement either of the below fixes.
Enable CORS on all routes
Because you've imported and used the cors package like so:
var cors = require('cors');
// ...
app.use(cors);
You've attached the cors constructor to the Express application rather than an instance of the cors middleware (You are calling cors(options) with cors(request)). The options object and its properties are covered in the documentation.
In its most basic form, you can use no configuration to allow CORS on all requests:
app.use(cors())
However, this is effectively the same as just manually setting the CORS headers yourself to * along with some other headers.
This is unsecure and goes against the point of CORS. You should instead configure it so that you only accept a handful of origins related to your project.
/** The current project's ID */
export const PROJECT_ID = JSON.parse(process.env.FIREBASE_CONFIG).projectId;
/** Array of permitted origins for CORS */
export const CORS_ALLOWED_ORIGINS = [
"https://my.custom.domain", // 0+ custom domains related to your project
`https://${PROJECT_ID}.firebaseapp.com`, // legacy Firebase Hosting domain
`https://${PROJECT_ID}.web.app`, // modern Firebase Hosting domain
...(process.env.NODE_ENV === "production"
? []
: ["localhost", "undefined"] // permit CORS on localhost, only while emulated
),
];
app.use(cors({ origin: CORS_ALLOWED_ORIGINS }))
Enable CORS only on /create_table
Similar to above, you've attached the cors() middleware to the /create_table route using:
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) { /* ... */ });
Here, dynamicCorsOptions is undefined (at least in the code you've shared) which will use the CORS middleware on requests to POST /create_table. However, you need to handle OPTIONS /create_table too.
// handle preflight requests
app.options('/create_table', cors(dynamicCorsOptions));
// handle actual requests
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) { /* ... */ });
You can even use cors({ origin: CORS_ALLOWED_ORIGINS }) from the above section for this.
Other points
The Functions Framework (that runs your function), as documented here, parses the body of the request for you if it is set with the appropriate headers. This means you don't need app.use(express.json()).
Your code calls createTable() but doesn't handle if it fails which will throw an unhandled Promise exception and terminate your function. You can either handle this case using catch() or the try/catch block in the next snippet:
createTable()
.catch((err) => {
console.error("Failed to create table: " + err.code || err.message, err);
res.status(500)
.send("Failed to create table with unknown error");
});
Currently the execution of your /create_table handler jumps around quite a bit, I propose rearranging it for readability:
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) {
'use strict';
// this could be moved outside of the handler
async function groupUp(requestBody) {
const groups = [];
for (let key in requestBody) {
const { name, type } = requestBody[key];
groups.push({ name, type });
}
return groups;
}
// this could be moved outside of the handler
async function createTableInDataset(datasetId, schema) {
const tableId = /* generate table ID */;
const [table] = await bigquery
.dataset(datasetId)
.createTable(tableId, {
schema,
location: 'US',
});
return table.id;
}
async function createTable() {
try {
const schema = await groupUp(req.body);
const createdTableId = createTableInDataset('denanse', schema);
console.log(`Table ${createdTableId} created.`);
res.status(201)
.send(`Table ${createdTableId} created.`);
} catch (err) {
console.error("Failed to create table: " + err.code || err.message, err);
res.status(500)
.send("Failed to create table with unknown error");
}
}
createTable();
});

How to use Botkit v4+ with custom express server for Slack bot

For Botkit v0.7.4, a custom express server can be used as follows
module.exports = function(webserver, controller) {
webserver.post('/slack/receive', function(req, res) {
res.status(200);
res.send('ok');
controller.handleWebhookPayload(req, res);
});
return webserver;
}
is something similar available for the latest version also.
Got the above sample from here
So far, I've got this
const adapter: SlackAdapter = new SlackAdapter({
getTokenForTeam,
getBotUserByTeam,
clientId: config.get('slack.clientId'),
clientSecret: config.get('slack.clientSecret'),
clientSigningSecret: config.get('slack.signingSecret'),
scopes: ['bot', 'team:read', 'users:read', 'users:read.email', 'chat:write:bot'],
redirectUri: config.get('slack.redirectUri')
});
adapter.use(new SlackEventMiddleware());
adapter.use(new SlackMessageTypeMiddleware());
// webserver is an express app - like so - const webserver = express();
const controller = new Botkit({
adapter,
webserver,
webhook_uri: '/slack/receive'
});
controller.ready(() => controller.loadModules('./features'));
How to setup the /slack/receive route so that the challenge verification when activating the events API and all further events emitted from Slack will be handled properly

How to access data in Parse Server via Cloud Code?

I try to make queries using the cloud code feature of our Parse server. Unfortunately we could not retrieve any data from the database. Our code looks as follows:
main.js:
Parse.Cloud.define('test', function(request, response) {
var user = request.user;
var token = user.getSessionToken();
var query = new Parse.Query('Carpark');
query.first({ sessionToken: token }) // pass the session token to find()
.then(function(messages) {
response.success(messages);
}, function(error) {
response.error(error);
});
});
index.js:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var api = new ParseServer({
databaseURI: 'mongodb://parse-server:[...]#localhost:27017/[...]',
cloud: __dirname + '/cloud/main.js',
appId: '[...]',
masterKey: '[...], //Add your master key here. Keep it secret!
serverURL: 'https://backend.[...]/parse', // Don't forget to change to https if needed
publicServerURL: 'https://backend.[...]/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
//var basicAuth = require('basic-auth-connect');
//app.use(basicAuth('triveme', 'triveme'));
app.use('/', express.static(path.join(__dirname, '/public')));
app.use('/parse', api);
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = 61004;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Example request from iOS-App:
PFCloud.callFunction(inBackground: "test", withParameters: nil) {
(response, error) -> Void in
if let response = response {
let result = response
print("Cloud data:", result )
}
if error != nil {
print(error ?? "default cloud function error")
}
}
I don't get any feedback from server (no response and no error). What is a possible problem of my issue?
Log request with verbose = 1:
REQUEST for [POST] /parse/functions/test: {} method=POST, url=/parse/functions/test, host=localhost:61004, accept=*/*, x-parse-session-token=[...], x-parse-application-id=[...].platform.dev2, x-parse-installation-id=[...], x-parse-os-version=10.2 (16D32), accept-language=en-us, accept-encoding=gzip, deflate, x-parse-client-version=i1.14.2, user-agent=trive.park/8 CFNetwork/808.2.16 Darwin/16.4.0, x-parse-app-build-version=8, x-parse-app-display-version=1.0, x-forwarded-for=[...], x-forwarded-host=backend.[...], x-forwarded-server=backend.[...], connection=Keep-Alive, content-length=0,
Log Response:
4|trive-pa | error: Failed running cloud function test for user nZ76ZimELw with:
4|trive-pa | Input: {}
4|trive-pa | Error: {"code":141,"message":{"code":100,"message":"XMLHttpRequest failed: \"Unable to connect to the Parse API\""}} functionName=test, code=141, code=100, message=XMLHttpRequest failed: "Unable to connect to the Parse API", user=nZ76ZimELw
4|trive-pa | error: Error generating response. ParseError {
4|trive-pa | code: 141,
4|trive-pa | message:
4|trive-pa | ParseError {
4|trive-pa | code: 100,
4|trive-pa | message: 'XMLHttpRequest failed: "Unable to connect to the Parse API"' } } code=141, code=100, message=XMLHttpRequest failed: "Unable to connect to the Parse API"
4|trive-pa | [object Object]
parse-server version: 2.2.23
self hosted on Apache Server
MongoDB

socket emit an event on http PUT

I am using expressjs, nedb, and socket.io. Various (non-browser) clients are able to PUT new values into the db successfully. When that happens, I want a message emitted to all browsers connected to the server. I have the following code which is currently not sending a message back to the browser.
// on the server
//***************************************************************
// reachable to the world at http://server/foo
// clients can PUT data into the db
app.put('/foo', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
io.sockets.emit('PUT a new value', { added: newDoc._id });
res.send('Success! Find it again with id: ' + newDoc._id);
});
});
// reachable to the world at http://server/
// browser shows a dashboard of events
app.get('/', function(req, res, next) {
// code to serve the dashboard here
});
io.sockets.on('connection', function (socket) {
socket.on('foo', function (data) {
io.sockets.emit('PUT a new value', data);
})
});
// in the browser
//***************************************************************
var socket = io.connect('/');
socket.on('PUT a new value', function (data) {
console.log(data);
});
Data get inserted into the db successfully from different non-browser clients, but the connected browser doesn't receive an update.
What am I doing wrong?
I found a solution which I don't like at all but it works. We can add io object to req or to res in the middleware like that:
app.use(function (req, res, next) {
req.io = io;
next();
});
before app.use('/', routes) and then in our router module we "import" the io object:
app.put('/foo', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
var io = req.io; // HERE !!!
io.sockets.emit('PUT a new value', { added: newDoc._id });
res.send('Success! Find it again with id: ' + newDoc._id);
});
});
I know, I know... let's find something else :-)
I have the following app structure generated by express generator. I start the app with $ DEBUG=foo:* npm start
.
|____app.js
|____bin
| |____www
|____data
|____LICENSE
|____node_modules
|____package.json
|____public
| |____stylesheets
| |____javascripts
| |____images
|____README.md
|____routes
| |____index.js
| |____readings.js
| |____sensors.js
| |____users.js
|____views
| |____error.hjs
| |____index.hjs
In app.js
var express = require('express');
var app = express();
var io = require('socket.io')();
app.io = io;
// notice the `(io)` for the routes that need to be socket-aware
var routes = require('./routes/index');
var users = require('./routes/users');
var sensors = require('./routes/sensors');
var readings = require('./routes/readings')(io);
…
// start listening with socket.io
app.io.on('connection', function(socket){
console.log('a user connected');
});
module.exports = app;
Then in ./routes/readings.js
var express = require('express');
var app = express();
var router = express.Router();
module.exports = function(io) {
router.put('/', jsonParser, function(req, res, next) {
if (!req.body) return res.sendStatus(400);
db.insert(req.body, function (err, newDoc) {
io.emit("reading", {id: newDoc._id});
res.send('Success PUTting data! id: ' + newDoc._id);
});
});
return router;
}
Finally, in the index.hjs template for the client-side
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('reading', function (data) {
console.log(data);
});
</script>
The above works. When data are inserted into the db via an http PUT (see readings.js), an event is emitted by io.emit('reading', data) and the browser receives that event and shows it in the console with socket.on('reading', function (data) { … });

npm restful api suddenly no longer working

I followed this tutorial to create a restful api with npm and postgres
Designing a RESTful API With Node and Postgres
I got everything to work without a problem, closed the server and went to other things.. when I got back, the routing stopped working suddenly giving 404 error.. I checked everything related to routing and I can't find the problem!
When I connect to localhost:3000 I get the correct express homepage
but when I try to access the api, localhost:3000/api/patients the 404 error page appears
Here is my code
index.js
var express = require('express');
var router = express.Router();
var db = require('../queries');
router.get('/api/patients', db.getAllPatients);
module.exports = router;
queries.js
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/maindb'
var db = pgp(connectionString);
module.exports = {
getAllPatients: getAllPatients
}
function getAllPatients(req, res, next) {
db.any('select * from patients where deleted = false')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL patients'
});
})
.catch(function (err) {
return next(err);
});
}
It seems something was wrong with express installation, something corrupted it.
I recreated the project from point zero and specified which version of express and bluebird to install, and everything seems to work fine without any problems.