Connect to couchDB with Javascript (Server Side) - javascript

I have the following code below, where I use Restify to create a node.js server and create routes. I want to connect to CouchDB to perform GET, POST, DELETE, PUT actions.
var restify = require("restify");
var server = restify.createServer();
server.listen(8080, function(){
console.log("incoming requests");
});
server.get('/users', function(req, res){
//CONNECT TO COUCHDB HERE
console.log("Got it!");
res.end();
});}
Any idea how I can connect and retrieve my data?
Thanks in advance.

You can use the JQuery plugin to connect to CoachDB. You can look through the below links to get more details
http://www.couchbase.org/community/articles/couchdb/recipes/3
http://java.dzone.com/news/couchdb-jquery-plugin

Related

Nodejs webhook server on local machine

So I have this long confusion about creating webhook API for my local app. This project is for learning purpose only so I need to understand what is the difference between simple REST API and webhook, in terms of implementation. I know the difference in terms of working but I can't get the technical difference.
For example, when I use Firebase in my web app and use the real-time database to get the updated values on the client-side, it works seamlessly and I don't need to make the POST or GET call every second or minute. It gets updated instantaneously. I know they might not be using webhook as such but rather using web-socket to keep the connection open between a client web app.
Okay now back to the webhook on the local machine - How can I create my own webhook server where the client can hook to the endpoint and get updates automatically.
Let me share some code
WebHook NodeJS server
// Require express and body-parser
const express = require("express")
const bodyParser = require("body-parser")
// Initialize express and define a port
const app = express()
const PORT = 3000
// Tell express to use body-parser's JSON parsing
app.use(bodyParser.json())
// Start express on the defined port
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`))
app.use(bodyParser.json())
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
var headers = {};
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
res.writeHead(200, headers);
res.end();
} else {
next();
}
})
const processSomething = callback => {
setTimeout(callback, 1000);
}
app.post("/hook", (req, res) => {
console.log(req.body) // Call your action on the request here
processSomething(() => {
res.status(200).send({
id: "ABC123",
message: "New record added!"
});
});
})
Web client running
index.html -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webhook Test Client</title>
</head>
<body>
<h1>Hello World</h1>
<div class="result">Data</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.post("http://localhost:3000/hook", function (data) {
console.log("data -- >",data);
$(".result").html("data -- > " + data);
});
</script>
</body>
</html>
nodejs to server the page -
const express = require('express'),
app = express(),
server = app.listen(1000);
app.use(express.static('public'));
console.log("server running...");
I have seen so many tutorials on Medium or other tech blogs but they mostly talk about connecting to webhook API hosted somewhere on a webserver that they have built as service or something.
So far I have understood and not understood is that.
I can't make webhook API call from the web client.
Only nodejs client-server can make webhook calls to the webhook endpoint. What I mean by this is - in my example webhook can't be called from HTML page but server serving that page can make the call. Maybe I am wrong.
Webhook is not so different from REST API.
Webhook is not made for the web client.
I will update this question as I get relevant replies and testing them.
Why I am interested in webhook because I wanted to create an API where the user doesn't have to make calls to an API to get an update but at the same time the API can be used from the web client, like firebase but avoid WebSocket at the same time. Or can I avoid WebSocket?
Edit: - So I got confirmation on webhooks are designed for server-to-server communication.
Most of the demos available online are using githud, discord, zapier, etc to create webhooks. Can you please share where we can just make custom webhooks without using third party libs ?

How to send commands from client to server with Socket.io

I would like to send commands from client to server example change image url or label text. I have managed to get the connection working between server & client and the button clicks to work, but i cant manipulate the DOM from the index.js file. Is there a solid way to do this? My client side uses PHP to get data from mySQL database and i'd like to pass that data as array to server and render to view. Here is my code so far:
server: index.js -
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
app.use(express.static(__dirname));
});
//This is auto initiated event when Client connects to Your Machien.
io.on('connection', function(client) {
console.log('Client connected...');
client.on('test',function(msg){
console.log("i can see this in cmd console");
// i would like to do like this but it says "document is not defined"
//document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
});
});
http.listen(3000,function(){
console.log("Listening on 3000");
});
client: app.js -
$(document).ready(function () {
$("#button1").click(function(){
socket.emit('test',$("#someinput").val());
});
});
I would like it to work like this rather:
server: app.js -
$(document).ready(function () {
var socket = io.connect('http://192.168.2.65:3000');
socket.on('test',function(msg){
$("#mediaContainer").append(msg);
console.log("i cant get this to work");
});
});
Thanks :)
Got it to work. Had to make a socket.emit inside the socket.on that catch it with another server javascript file like this:
index.js:
client.on('test',function(value){
io.sockets.emit('testi1',value);
});
app.js:
socket.on('testi1',function(msg){
$("#mediaContainer").append(msg + '<br /><br />');
});
There are two sides to socket.io, BackEnd and FrontEnd.
In the code above, you tried to manipulate the DOM like document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
but this is the FrontEnd part.
How socket.io works is you use js provided by socket in the FrontEnd to emit something to the server where the socket in the BackEnd will be listening to. Then, you emit something from BackEnd in response to the received emission. You also add a listener at the FrontEnd part to this BackEnd emission and finally manipulate the DOM according to the received emission.
FrontEnd
$(document).ready(function () {
var socket = io.connect('http://192.168.2.65:3000');
$("#button1").click(function(){
socket.emit('test',$("#someinput").val());
});
socket.on('test',function(msg){
$("#mediaContainer").append(msg);
});
});
BackEnd
io.on('connection', function(client) {
console.log('Client connected...');
client.on('test',function(msg){
// If you want all including the sender to get emission
client.emit('test', msg);
// If you want all excluding the sender to get emission
client.broadcast.emit('test', msg);
});
});
This should work. Cheers!!

retain query string after Stormpath authentication and authorization in node express site

I have a node express app , using express-stormpath for authentication/authorization
I have a GET route which is called with certain jquery parameters.
If the user is logged in everything is working as expected.
If not the user login screen is shown.
After stormpath authentication and authorization is done my query params are lost.
Is there any way to retain those?
app.get('/myRoute', stormpath.groupsRequired(['admin']), function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});
after authentication req.query is {}.
Any ideas?
Thank you for the question, I work at Stormpath and I'm more than happy to help. Our express-stormpath library is open source, and we're always happy to fix bugs and review pull requests.
Can you tell me which version of our library you are using? At the moment I'm not able to reproduce the problem you are seeing. Here is a quick example that I put together with the latest version, 3.0.1:
'use strict';
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
var port = process.env.PORT || 3000;
app.use(stormpath.init(app));
app.get('/admins', stormpath.groupsRequired(['admins']), function(req, res){
res.json(req.query);
});
app.on('stormpath.ready',function () {
console.log('Stormpath Ready');
});
app.listen(port, function () {
console.log('Server listening on http://localhost:' + port);
});
With this example, I do the following:
1.) Assert that I'm not logged in, by deleting all my cookies for localhost.
2.) Type /admin?foo=bar into the URL bar.
3.) I am redirected to the login page.
4.) I login with valid credentials.
5.) I am redirected to /admins?foo=bar, as expected, and I see the req.query object in the body of the page that is rendered. This is only true if the user is in the admins group, if they are not I will see the "Unauthorized" error message page.
Can you compare my steps and my example to your application, and let us know if there are any differences? Thanks!
I don't think that stormpath is removing query from request.
But we can check it by adding middlewhare before stormpath initialization:
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// binding middleware to assign req.query to req.q param
app.use(function(req, res, next) {
req.QUERY = req.query;
next();
});
function restoreQuery(req, res, next) {
req.query = req.QUERY;
next();
}
app.use(stormpath.init(app, {
// Optional configuration options.
}));
app.get('/myRoute',
stormpath.groupsRequired(['admin']),
restoreQuery,
function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});

Client not updating realtime with Socket.io and Node.js

Why isn't my client side updating automatically using socket.io and node.js?
My backend accepts JSON POST requests from PHP, then it emits the data to all connected devices.
My backend code
app.post('/', function (req, res) {
console.log(req.body);
subdata = req.body;
res.send('ok');
});
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('info', subdata);
});
Client side
<script>
var socket = io.connect('http://127.0.0.1:3000/');
socket.on('info', function (data) {
console.log(data);
});
</script>
That's because you only ever emit once when a new socket.io connection is made. If the app.post callback is called again, there's nothing to emit another message from socket.io.
You want to emit from within your app.post callback, and stop using global variables.

How does nodejs usually manipulate DOM from the backend without using socket

Usually what I would do is
In backend
socket.emit("manipulate", data);
In frontend
socket.on("manipulate", data);
So that you can signal Jquery to manipulate the DOM in frontend
However because I want to manipulate the DOM in app.js where
FILES
app.js
backend.js
ui.js
app.js
app.post('/test', function(req, res){
res.sendfile(__dirname + '/views/test.html');
Backend.manipulate(req.body, function(err, data){
if (err) throw err;
// how do I manipulate DOM here
});
});
backend.js
exports.listen = function(server){
io = socketio.listen(server);
io.set('log level', 2);
io.sockets.on('connection', function(socket){
});
}
I don't have access to socket, and I can't move exports.listen as all my socket manipulation is there.
Any advice would be appreciated
Edit:
For clarification on the use case, say that I have a registration form in the front end, the registration is submit through POST, and POST calls a function in backend.js that register the user, after backend.js succesfully register the user it would like to send a message to the user, how would that message normally be display in frontend?

Categories