Run nodejs script on button click - javascript

please can someone explain how I can made this nodejs script run when a button is clicked?
var Twit = require('twit');
var t = new Twit({
consumer_key: '******',
consumer_secret: '******',
access_token: '******',
access_token_secret: '******',
});
t.post('statuses/update', {status:'hello world'},function(err, data, response){
console.log(data);
});
Currently I get:
Uncaught ReferenceError: require is not defined
Thanks

You will need to have a NodeJS process running as a server in which a callback can be hooked to an API endpoint which will then be run when you click on a button in a website.
Client gets HTML with button (from a webserver of any type)
Client clicks on button
HTTP request is sent to NodeJS server at a particular url (yourip.com/yourscript)
NodeJS server calls a function that you assigned to that particular URL

NodeJS is used on the server-side, and can be described as an extension of JavaScript which can do more stuff, like file operations.
Normal JavaScript is used on the client-side.
Therefore, you cannot just use nodeJS in the browser, because the browser is lacking features that nodeJS offers. What you can do is use nodeJS to build an API and connect the API to the client-side script. You will need a server for this to work, though.

Related

How to call simple Node.js script from Javascript?

I'm trying to create a basic web application with SMS capability. However, I'm a bit stumped. I'm using Twilio's SMS service, but it utilizes Node.js. Obviously, you can run it with a terminal command such as "node send_text.js", but I'm trying to make the call to the send_text.js file without using the terminal command.
I understand that you can use Express to host your web application, but I'm not too sure how you would go about calling a Node.js file from javascript.
The following is the send_text.js file I would like to call from Javascript.
var twilio = require('twilio');
// Find your account sid and auth token in your Twilio account Console.
var client = new twilio('TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN');
// Send the text message.
client.messages.create({
to: 'YOUR_NUMBER',
from: 'YOUR_TWILIO_NUMBER',
body: 'Hello from Twilio!'
});
Essentially, I'll detect a change in data using Javascript, and when the change is detected, call the send_text.js file to send a text to the user.
EDIT:
I've tried my own basic implementation of using require, but it doesn't seem to work properly.
Here's what I have in my index.html file:
<script type="text/javascript" src="send_text.js"></script>
<input type="button" onclick="sendText()" value="run external javascript">
And when I try to call the send_text.js, which has the following, I do not get any text message sent:
function sendText()
{
var twilio = require('twilio');
// Find your account sid and auth token in your Twilio account Console.
var client = new twilio('TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN');
// Send the text message.
client.messages.create({
to: 'YOUR_NUMBER',
from: 'YOUR_TWILIO_NUMBER',
body: 'Hello from Twilio!'
});
}
However, the code does work if send_text.js has the following:
function sendText()
{
alert("Hello world")
}
You can use the child process in Nodejs to call a js script from another js file using childProcess.fork(filepath);
according to the question I understood. should look something like this
let childProcess = require('child_process');
childProcess.fork('./send_text.js);
for more information see
https://nodejs.org/api/child_process.html
The code you're showing us is some example source code. You can copy and paste the relevant parts directly into your Express app.
Twilio developer evangelist here.
You could use a tool like Netlify--here's a tutorial on how to send text messages from a static website using Twilio, Netlify, and Serverless Functions.
You could also use Twilio's serverless environment for web apps called Twilio Functions--here's a tutorial on that using the Twilio CLI as well.
Similarly, you could send a SMS from a Gatsby website with Serverless Functions and React.js, or use an AWS Lambda Function to send a SMS.

Simple connection to mongodb in react app

I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.
I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:
mongodb+srv://matt:passwprd#cluster0-jlasm.mongodb.net/test
Now, all I want to do is to send JSON data from the form to mongo but I don't know how.
When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
The entire application crashes:
./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'
I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.
My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.
Please help me because I am loosing my nerves.
You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).
Then when returning a request from server send the data required then use your react client to handle the data recived
Hope it works!
handleSubmit(){
let databody = {
"name": this.state.name,
// Remaining form Data
}
return fetch('mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
// Form Fields
<input type="submit" value="Save" />
</form>
</div>
);
}
To connect to MongoDb in javascript, you must use a node.js server.
It is therefore impossible to directly connect your React application to your MongoDb cluster.
For more information, visit the official MongoDb documentation
First you need to create a React.js on the frontend and then node.js on the backend web application.
Then, you need to connect your mongodb collection to your Node.js server.
Then you can send your form data to your node.js server and your node.js server will send your form data to your mongodb collection.
Making a full-stack React-NodeJS-MongoDB web application can be a little challenging, if you do not know NodeJS. So you might first start with EJS-NodeJS-MongoDB web application. But in any case, here are links for your question:
https://www.youtube.com/watch?v=3isCTSUdXaQ&t=2248s
https://www.youtube.com/watch?v=Oa0pMn0tvU4&t=1316s

Working with API's in Node, security of var

I'm a php developer learning how to work with Node.
When you work with php and a private API which requires an API key, you're kind of safe since you can't view PHP code in the developers console.
But now I'm working with an API in Node which has this structure.
var AdwordsUser = require('node-adwords-es5');
var user = new AdwordsUser({
developerToken: 'INSERT DEVELOPER TOKEN', //your adwords developerToken
userAgent: 'Geen', //any company name
clientCustomerId: 'INSERT CLIENT ID', //the Adwords Account id (e.g. 123-123-123)
client_id: 'INSERT_OAUTH2_CLIENT_ID_HERE', //this is the api console client_id
client_secret: 'INSERT_OAUTH2_CLIENT_SECRET_HERE',
refresh_token: 'INSERT_OAUTH2_REFRESH_TOKEN_HERE'
});
Since this is JavaScript I assume you will be able to see all of this in the developers console. Which is not safe?
How do people usually solve this, or am I worrying for nothing?
Node runs on server side so its not possible to view it in the web console. you can only view the data coming from node server on HTTP or socket call.so relax and happy coding .

Node.js Express: Passing data from URL and session into served JavaScript file

I've been building a web-socket application in which the client opens a link to a game instance, and then the server attempts to connect the client to the respective Socket.io room on which the game will transmit information. For example, connecting to '/game/abc' would load up the game page and connect the socket on the page to the 'abc' room on the server.
The problem with this is getting the client JavaScript file to emit the game ID and the username of the user connecting. I want it to act in the following way:
Client.js
var socket = io();
socket.emit("newUser", username, gameID);
I have managed to accomplish this by passing both my client.html and client.js page through an Express template renderer:
Server.js
app.get(/^\/game\/([a-zA-Z0-9]*)$/, function(req, res){
var game = req.params[0];
var user = req.session.name; //gets username stored in session
res.render("client.html", {username: user, gameName: game});
});
app.get(/game\/(.*)\/client.js/, function(req,res){
res.render("client.js", {username: req.session.name, gameName: req.params[0]});
});
The second app.get() allows for the gameName to be passed along to client.js through client.html in the form of a parameter in the url.
Client.html
<script src="{{gameName}}/client.js"></script>
Finally after two passes, the game ID and username both are put into client.js by the template engine.
Client.js
var socket = io();
socket.emit("newUser", "{{username}}", "{{gameName}}");
//leads to socket.emit("newUser", "user", "abc"); when passed through renderer
Although this gets the job done, it feels incredibly convoluted and indirect. I've looked up alternatives to this, with the answer at node.js express rendering inside included js files recommending to use AJAX calls. However, I have not been able to figure out how to exactly configure such an AJAX call. Is there a more effective way to overcome this problem?
You can simplify all of this and avoid rendering the templates in Express to pass that variable in this case.
You already have the gave name available to your client-side code in the window.location object. You can either parse it manually with a simple regex (in this case) or you can use something that is called a client-side router which there are a lot to choose from.
There is one simple client-side router inspired by Express.js: Page.js, which would allow you to use a very similar code that you use right now in Express.
Many client-side frameworks have routers build in.

Authenticating and fetching data from couchdb using jQuery

I have a web app served by cherrypy. Within this app, I would like to fetch some data from a couchdb server, preferably using jquery. I am having trouble to authenticate into the server. When using:
$.couch.login({
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
It sends the login request to the cherrypy server, not the couchdb. According to this, I can use jquery.ajax settings and therefore I have tried using:
$.couch.login({
url: 'http://127.0.0.1:5984',
name: 'usename',
password: 'password',
success: function() {
console.log('Ready!');
}
});
but it does not seem to work.
Any ideas? In addition, can anybody point me to good tutorial or simple web app developed in a similar fashion, i.e. a "standard" web page (not a couchapp), which contains jquery that gets info from couch.
What you are currently doing is telling jquery.couch.js to login against that url. (It needs to POST to /_session)
I believe you need to set up the urlPrefix property on $.couch.
$.couch.urlPrefix = "http://localhost:5984/"; // run this before anything else with $.couch
Don't forget that inside a browser, JavaScript enforces the same origin policy. Since the HTML page is presumably not being loaded from port 5984, you'll have figure out some clever way around it, such as CORS or mod_proxy.

Categories