简体   繁体   中英

Running a node.js file from website

I have recently started using the Twilio platform to send SMS to my users. I am perfectly able to run the node.js file from the node terminal with the command:

 node twilio.js 

Now, my goal is to be able to send those SMS, but from my website. For instance, when the user provides his phone number and presses the "Send sms" button. How can I achieve this? I have been looking this up for a while and I came across Express platform, ajax post requests, http server, etc. But, I can't figure out how to use them. I currently make many ajax requests (POST and GET) on my site, but I'm not able to make a request to a node file.

Thanks in advance,

Here is the twilio.js file:

  // Twilio Credentials var accountSid = 'ACCOUNT SID'; var authToken = 'ACCOUNT TOKEN'; //require the Twilio module and create a REST client var client = require('twilio')(accountSid, authToken); client.messages.create({ to: 'TO', from: 'FROM', body: 'Message sent from Twilio!', }, function (err, message) { console.log(message.sid); }); 

Being able to run any arbitrary script on your server from a webpage would be a huge security risk - don't do that. I'm not sure where you're hosting your site, or what technology stack you're running your site on, but since you mentioned Express and Node -- if you're using Express I'd recommend that you setup a route that handles an ajax request. When someone presses 'Send SMS' you send an ajax request to that route, and in the handler that gets invoked you place the Twilio logic.

Here is a very simple way to setup an Express request that calls you node module:

twilio.js:

// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';

//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);

function sendSms(callback) {
    client.messages.create({
        to: 'TO',
        from: 'FROM',
        body: 'Message sent from Twilio!',
    }, callback);
}

// Export this function as a node module so that you can require it elsewhere
module.exports = sendSms;

Here is a good start for Express.

server.js:

var express = require('express');
var app = express();

// Requiring that function that you exported
var twilio = require('/path/to/twilio.js');

// Creating a controller for the get request: localhost:8081/send/sms
app.get('/send/sms', function (req, res) {
   twilio(function(err, message) {
     if (err) res.send(err);
     res.send('Message sent: ' + message);
   });
});

// Creating an HTTP server that listens on port 8081 (localhost:8081)
var server = app.listen(8081, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log("Example app listening at http://%s:%s", host, port);

});

Then you can run node server.js , go to your browser and go to the url: localhost:8081/send/sms and your message will be sent :)

I'd make it so the client sends a HTTP POST request to the server, and then the server will send the message on behalf of the client.

Easiest way is to use express. I'm a bit unsure of how you're serving your website from a Node.js app without using express. Do you have a custom solution or only a non-connected from end, or something like heroku or something? In any case, you can create a route that processes posts with the following:

app.post("send_twilio_message_route", function(req,res){ // this receives the post request -- process here });

^ Note that doesn't actually create the express app. See my link below and they give examples of some of the nitty gritty and syntax.

So the above would be on the server, in your Node.js app. From the front-end client code that runs in the browser, you need to create a post. The easiest way and most likely way to do it is through $.post in Jquery. if you are using Angular there's a slightly different syntax but it's the same idea. You call post, point it to a url, and put in the body data.

Make the body of the post request contain data such the message, phone numbers, authentication token maybe.

See this to be able to get the body from a post request and some more implementation details of how to set it up: How to retrieve POST query parameters?

Depending on the nature of what you're doing you might consider having the sms processing stuff run separate from the actual web service. I would create the sms unique stuff as its own module and have a function retrieve the router so that you can mount is onto the app and move it about later. This might be overkill if you're doing something small, but I'm basically encouraging you to at the start put thought into isolating your services of your website, else you will create a mess. That being said, if it's just a small thing and just for you it might not matter. Depends on your needs.

  • Important: I highly encourage you to think about the malicious user aka me. If you don't add any authentication in the post body (or you could include it in the url but I wouldn't do that although it's equivalent), a malicious client could totally be a jerk and expend all of your twilio resources. So once you get it basic up in running, before deploying it to anything that people will see it, I recommend you add authentication and rate limiting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM