How to connect my website to my node app? - javascript

So I am trying to send test data to my node app using ajax. I'm not sure what I'm doing wrong to post the information. I have added this to my script to my html:
index.html
<script type="text/javascript">
jQuery(function() {
console.log('hello');
var $ = jQuery;
$(window).ready(function() {
console.log('hello');
$.ajax({
dataType: 'jsonp',
xhrFields: {
withCredentials: true,
},
url: 'http://localhost:3000',
data: '{"data": "TEST"}',
type: 'POST',
success: function () {
console.log('Success: ');
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
},
});
});
});
</script>
I am trying to receive this information from my node app but I'm not sure how to.
server.js
var express = require('express')
, cors = require('cors')
, app = express()
, http = require('http');
app.use(cors());
var server = http.createServer(app, function(req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log(body);
res(body);
});
}).listen(3000, function(){
console.log('CORS-enabled web server listening on port 80');
});
However, I keep getting this error on website's console:
'GET http://localhost:3000/?callback=jQuery214011563337640836835_1442781076103&{%22data%22:%20%22TEST%22}&_=1442781076104 n.ajaxTransport.a.send # jquery.js:8698n.extend.ajax # jquery.js:8166(anonymous function) # final.html:534n.Callbacks.j # jquery.js:3099n.Callbacks.k.fireWith # jquery.js:3211n.extend.ready # jquery.js:3417I # jquery.js:3433
final.html:550 Error: undefined'
If this is successful I am trying to create a form that posts the input to my node app that can process it with stripe.

I recommend following the Express JS Getting Started guide found here: http://expressjs.com/starter/installing.html. Specifically, look at the sections on Express generator and Basic routing.
In your code, you are requiring the Express module, but not actually using it, and this module is the most robust way to handle posts in node.js.
If you still want to use the http module for handling post requests, check this out: Node.js server that accepts POST requests. It also has more information on using Express JS

Related

Using AJAX to call Node.js file to send SMS message

I'm new to Node.js but I understand that it's on the server-side. When I run my app.js file in Terminal, it sends the text message, but what I'm ultimately trying to do is have the user finish the form, and upon button press, send them a text message to verify their submission. I'm using the Twilio service to help accomplish this. It's currently not sending a message on button press.
Here's my app.js file:
var accountSid = process.env.TWILIO_ACCOUNT_SID;
var authToken = process.env.TWILIO_AUTH_TOKEN;
var client = require('twilio')(accountSid, authToken);
app.get('/testtwilio', function(req, res) {
client.messages.create({
to: "+1receivingNumber",
from: "+myTwilioNumber",
body: "Testing, testing, testing"
}, function(err, message) {
if (err) {
console.log(err);
} else {
console.log(message.sid);
}
});
})
And my Javascript file:
$('#buttons').on('click', function(e) {
$.ajax({
type: 'POST',
url: '/testtwilio',
data: {
"To": userCellPhone,
"From": "+1myTwilioNumber",
"Body": "Ahoy! Testing"
},
beforeSend: function(xhr) {
...
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
And lastly, my html button:
<button type="submit" id="buttons" class="buttons">SUBMIT</button>
Honestly, I'm not even sure this is possible, but I've been searching forever and can't really find any direct solution. Any help is appreciated!
Your app variable is undefined. If you want to use the express framework like in the tutorials you've followed, you need to register it in your app.js like follows:
var express = require('express');
var app = express();
Combined with the answers/comments about POST, that should see you on your way.
Nb. you'll need to install express in your node modules. From the command line in your root directory:
npm install --save express
nodeJs route expects GET. But your ajax makes POST request. Try:
app.post('/testtwilio', ...

How to send an email from a Webix application using sendmail of node JS server at the backend

I want to send an email from a webix application by clicking a button in the UI, which will send a post request through an ajax call to the node JS server at the backend.
The webix part looks like below:
{ id:'tb',
view: 'toolbar',
cols: [
{view:"button", id:"mail_btn", type:"icon", label:"SendEmail", tooltip:"Send an email", width:100, on: {onItemClick:function(){sendEmail()}} },
]
}
The callback function:
function sendEmail() {
var bodypart = {"message" : "This is a test mail"};
$.ajax({
type: 'POST',
url: '/appl/email',
data: bodypart,
success: function (data) {
console.log("success");
},
error: function(err){
console.log(err);
}
});
}
}
The above ajax call sends a request to the node JS where I am using sendmail npm package to achieve this. The code looks like below :
var sendmail = require('sendmail')();
app.post('/appl/email', sendmail());
function sendEmail() {
sendmail({
from: 'xyz#support.com',
to: 'abc#support.com',
subject: 'test sendmail',
html: 'Mail of test sendmail ',
}, function(err, reply) {
console.log(err && err.stack);
console.dir(reply);
});
}
However, I am getting below error :
Error: Route.post() requires callback functions but got a [object Undefined]
Is there a way to send email from webix itself without sending the request to node JS server ?
Or else how to use the sendmail npm package to achieve this the way I am trying ?
Any help would be appreciated.
Your issue is not in the way you are using sendmail, but rather in the way you are using express routes.
Here is a sample code I just whipped up that gave me the same error you got in your code.
const express = require('express');
const app = express();
app.get('/', doSomething());
function doSomething() {
console.log('this is a sample test');
}
app.listen(3000, () => console.log('server is running'));
The issue is that app.get, and the same would be true for app.post, has a certain signature it requires. The function that gets passed in is supposed to have the req and res arguments. You can also optionally add the next argument last.
This is how my above code would fixed.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
doSomething();
res.json('success');
});
function doSomething() {
console.log('this is a sample test');
}

How to make ajax get/post request in express server?

Below is my express server. I am trying to make a get request in ajax, but it turned out failed even though I required jquery at the beginning. It said $ is not defined Other than using jquery ajax, what else can I use to make an API call form RESTful API url?
var express = require('express');
var requestHandler = require('./requestHandler');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, '../client')));
app.get('/homepage', requestHandler.getData);
var port = process.env.PORT || 3000;
app.listen(port);
console.log("Server running at: http://localhost:" + port);
// request handler file:
var express = require('express');
var url = "http://jsonplaceholder.typicode.com/";
module.exports.getData = function (req, res){
$.ajax({
method: 'GET',
url: url+'posts',
success: function(data) {
console.log(data);
res.send(data);
}
});
}
module.exports.getComments = function(userId){
$.ajax({
method: 'GET',
url: url+'/comments',
success: function(data) {
console.log(data);
}
});
}
HTTP GET Request in Node.js Express
var http = require('http');
var options = {
host: 'www.google.com',
path: '/index.html'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
You need to understand things like:
expressjs is serverside code so it can't use jquery ajax like that.
jQuery.ajax() can only be used at view when you load your page in the browser.
You need to use some view engines like jade to create templates and use routers to push the view in the browser. When you have your view in the browser then you can make a reference to the script file which can contain your ajax code to let you have posts and comments.
More information.
Try something like this:
function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.getProjects();
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
Also please note. you will call this from an external JavaScript file. One the express server you will only have "routes" and from external javascript files you can perform HTTP calls on those routes.
Update
#Someone, the express framework is very popular to setup a web server in Node. You can use different render engines to render the view and pass information to the user. This is a very simple example from the Express website listening to two urls (/posts and /comments).
var express = require('express');
var app = express();
app.get('/posts', function (req, res) {
res.send('Render posts!');
});
app.get('/comments', function (req, res) {
res.send('Render comments');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Problems using Parse.Cloud.httpRequest with Express, says no such method for success:

I'm hitting a facebook graph search URL, in Parse Express. The call is made with a Parse.Cloud.httpRequest.
I get a 500 Internal Server Error response, and when I look in the logs I see:
an error saying that the httpRequest has no method named success: (even though the code i'm using is based right off examples on Parse.com).
The basic JSON data is there successfully retrieved but the error has prevented the function completing.
Here's the code, all tips appreciated:
// These two lines are required to initialize Express in Cloud Code.
var module = require('cloud/jsonml.js');
var Buffer = require('buffer').Buffer;
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
app.get('/hello', function(request, response) {
Parse.Cloud.httpRequest({
url: 'a-facebook-graph-url',
success: function(httpResponse) {
console.log(httpResponse.data);
response.success(httpResponse.data);
var xml = module.stringify(httpResponse.data);
var base64xml = xml.data.base64;
console.log(base64xml);
res.render('hello.ejs',{ message: base64xml });
},
error:function(httpResponse){
console.error('Error:' + httpResponse.message);
response.error("Failed to parse feed");
res.render('hello.ejs',{ message: httpResponse.message });
}
});
});
app.listen();
I just use promises. This seems to work for me:
Parse.Cloud.httpRequest({
url: 'a-facebook-graph-url'
}).then(function(httpResponse) {
console.log(httpResponse.text);
var xml = module.stringify(httpResponse.data);
var base64xml = xml.data.base64;
res.render('hello',
{
message: base64xml
});
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
More info from parse website here

How do I parse my JSON with external middleware now that Express doesn't carry a body parser?

How do I parse my JSON with external middleware now that Express doesn't carry a body parser?
For a while, I was using Express bodyParser to receive and respond to JSON posts to the server. Each time I started up the server, express said something about bodyParser being removed soon, and sure enough, I've updated and now JSON requests seem to be showing null.
So I didn't understand how middleware worked, and had followed an express tutorial to use the body parser. Now, using separate body parser middleware, it seems I'm doing it wrong.
Before, my syntax was:
app.use(express.bodyParser());
Now, with the module body-parser as middleware, it's like this:
app.use(bodyParser.json());
And an example as a whole:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
function listen() {
app.use(bodyParser.json());
app.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
console.log('User ' + username + ' is attempting login...');
validate(username, password, function (err, result) {
if (err) loginFail(req, res, err);
else loginSucceed(req, res, result);
});
});
app.listen(3333);
}
listen();
I tried express.json() as the middleware, but that triggers the fatal error:
Error: Most middleware (like json) is no longer bundled with Express
and must be installed separately. Please see
https://github.com/senchalabs/connect#middleware.
That link leads to the body-parser middleware that I'm using via app.use(bodyParser.json()).
Update:
Using bodyParser.json() results in no error, but the data values are null:
User undefined is attempting login...
My client code should be fine, but here it is for completeness:
function sendLogin() {
popLogCreds(creds);
var loginCredentials = {
"username": creds.username,
"password": creds.password
};
console.log("Sending login credentials: " +
JSON.stringify(loginCredentials, null, 4));
request = $.ajax({
url: "http://54.186.131.77:3333/login",
type: "POST",
crossDomain: true,
data: loginCredentials,
dataType: "json",
error: function () {
postError("Uh Oh! The Officeball server is down.");
},
success: function (data) {
var ParsedData = data;
sessionStorage.username = creds.username;
sessionStorage.password = creds.password;
sessionStorage.fname = ParsedData.fname;
sessionStorage.lname = ParsedData.lname;
sessionStorage.rank = ParsedData.rank;
console.log(sessionStorage);
window.location.replace("app.html");
}
});
}
Which results in:
Sending login credentials: {
"username": "jonathan#evisiion.com",
"password": "J******!"
}
And then the result is the POST's error output, which is, as above:
error : function () {
postError("Uh Oh! The Officeball server is down.");
}
Don't take that error message literally. Just means an error happened. The server is, in fact, getting that request, as shown up above.
By default, $.ajax() sends data URL-encoded as mentioned in the description of the processData option:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
The body-parser that corresponds to that Content-Type and format is urlencoded():
app.use(bodyParser.urlencoded());
If you'd rather use JSON for the request, you'll need to provide the data already formatted as such along with a matching contentType that bodyParser.json() recognizes:
request = $.ajax({
url: "http://54.186.131.77:3333/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType: 'application/json',
dataType: 'json'
// ...
});
Note for cross-domain: With these modifications, the server will have to handle preflight OPTIONS requests for the route.
And, note that a bodyParser isn't needed for HEAD or GET requests as the data is included in the URL rather than the body. Express parses that separately into req.query.
In your node code,
make sure you put these two lines of code
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
......then your other code follows..
enjoy...

Categories