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

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', ...

Related

Getting HTML instead of JSON from NodeJs

I am working on project containing app and landing pages. We are using Nodejs with Axios and VueJs for app part. But for landing pages, it is simple jQuery. I must do some API calls for landing pages, but I am not able to use NodeJs result in jQuery to serve data in my landing pages. I am new at NodeJs and these technologies.
Here are my codes:
my Routes :
const router = express.Router();
...
router.get('/api/items', myApiController.getItems);
NodeJs controller
module.exports.getItems = (req, res) => {
const response = myApiController.getItems();
if (response.status === 200) {
res.send({
status: 200,
data: response.data
})
} else {
res.send({
status: 404,
data: null
})
}
}
my main script :
$.get("/api/items", function(data, status){
alert("Data: " + data);
var mylist = $("#mylist");
$.each(data, function(item) {
mylist.append($("<option />").val(item.name).text(item.name));
});
});
Even if I am getting status:200 the nodejs is returning HTML of page 404.
I do not find the cause, And honestly I do not understand the reason. It seems it is try to get a page does not exist, but I am requesting a json from function.
I try to replace contoller method call by a trash json but nothing work.
Here is what I try:
router.get('/api/items', function(req, res){
console.log('cc');
return res.json([{
'toto': 'toto',
'tata': 'tata',
}]);
});
It seems routes definitions issue, but I do not know how to fix. Could this have something with express Router ? Could you please explain me and help me to fix this? Thanks
When you respond with a string, the content type will be HTML. Try this, which removes the res.json call:
router.get('/api/items', function(req, res){
console.log('cc');
return [{
'toto': 'toto',
'tata': 'tata',
}];
});

getting request data from getInitialProps()

I am trying to post data from a python script to a Next js server.
#python script
import requests
post_data = {'username':'bob', 'id' : 32}
# POST some form-encoded data:
post_response = requests.post(url='http://localhost:3000/foo', data=post_data)
I do get a request on a server, but I do not know how to retrieve the data in getInitalProps(). I have looked at the documentation but there seems to be no such information.
static async getInitialProps({props, req})
{
console.log('request data: ', req.data);
}
Crashed into the very same problem and found the solution well hidden in the Next.JS forums.
In short, first you need the Urlencoded Body Parser library to help parse the HTTP request object. Using npm to install it:
npm install --save urlencoded-body-parser
Then in your code file, you call its function to get an object with the post variables in it:
import parse from 'urlencoded-body-parser';
static async getInitialProps(context)
{
if (context.req.method === "POST") {
const data = await parse(context.req);
console.log("request data: ", data);
}
}
Results, based on question sample data:
{
"username": "bob",
"id" : "32"
}
It should be like this:
static getInitialProps ({ query: { data } }) {
console.log('request data: ', data);
}
please not that you also need to pass the data in server.js:
server.get('/foo', (req, res) => {
return app.render(req, res, '/pageFoo', req.query)
})

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');
}

trouble building react component that has ajax calls

I am trying to build a simple node.js app using reactjs tutorial on comment box example.
I am having trouble saving comments to database, which is mongodb.
Here's the code,
comment_box.jsx
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
var commBox = this;
$.ajax({
url: commBox.props.url,
dataType: 'json',
cache: false
}).done(function(data) {
commBox.setState({data: data});
});
},
handleCommentSubmit: function(comment) {
var commBox = this;
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: commBox.props.url,
dataType: 'json',
type: 'POST',
data: comment
}).done(function(data) {
commBox.setState({data: data});
});
},
api.js
//api for listing and posting comments
//bring comments model
var Comment = require('../models/comment.js');
exports.post = function(req, res, err) {
new Comment({comment: req.comment, author: req.author}).save(function() {
if(!err) {
console.log('saved');
}
else {
console.log('save failed');
}
});
}
exports.list = function(req, res) {
Comment.find(function(err, comments) {
res.send(comments);
});
}
router.js
var express = require('express');
var Router = express.Router();
var path = require('path');
var api = require('../controllers/api.js');
Router.get('/', api.list);
Router.post('/', api.post);
module.exports = Router;
server.js
// set up the RESTful API, handler methods are defined in api.js
app.use('/api/v1/*', require('./server/routes/router.js'));
The error is in exports.post in api.js the req doesn't come with body for some reason, I tried debugging with node inspector but couldn't see what the problem. Any help would be much appreciated. Please let me know if you need me post any further details to understand the question. Basically, in console I get error ERR_RESPONSE_EMPTY.
more details on the error,
I am running node server on my apple machine os x el capitan, routing is done by using expressjs, after I load the page react mounts the components which contains a comment form where you can get to add comments and post them. So ,here when I hit post button the ajax call should post the comment to the database and react component will get updated. But , the post call is not happening. In my comment_box.jsx code you can see the post call. the bit I posted here in server.js will handle the routes. and I have a router.js file and api.js that contains methods for posting and listing comments.
I was expecting when a comment is submitted, the form submit will trigger the react function to do the ajax call and update the database. But, it's not happening I get ERR_RESPONSE_EMPTY.

How to connect my website to my node app?

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

Categories