weixin_33699914 2017-09-07 02:32 采纳率: 0%
浏览 14

AJAX网址路径问题

I'm trying to use AJAX to call on a Node.js file to send a text message on button press. So when I type node app.js in the terminal the message sends to my phone, however, when I use a jQuery click event in my javascript file, it's no longer sending within the browser. I'm thinking the primary problem is within my index.js file and not the Node.js file, more specific, the actual URL path.

Here's my app.js file that contains the info to send the text message (app.js):

var accountSid = process.env.TWILIO_ACCOUNT_SID;
var authToken = process.env.TWILIO_AUTH_TOKEN;
var client = require('twilio')(accountSid, authToken);
var express = require('express');
var app = express();

client.messages.create({
  to: "+1...",
  from: "+1...",
  body: "Testing, testing, testing"
}).then((messsage) => console.log(message.sid));

My file that contains Javascript (index.js):

$("#buttons").click(function() {
  alert("Clicked.");

  $.ajax({
    url: "/app.js",
    type: "POST",
    beforeSend: function() {
      alert("testing");
    },
    success: function(result) {
      // $("#result").html(result);
      alert("  sss  ");
    }
  }).error(function() {
    alert("wrong");
  });
});

So my primary question is, is the URL suppose to be the location/name of the file you're trying to run? So far that's been my understanding, yet the message isn't being sent.

  • 写回答

2条回答 默认 最新

  • weixin_33697898 2017-09-07 03:06
    关注

    This isn't going to work. Your ajax request is going to be looking for a service that speaks http and running environment to execute your code, which you haven't provided.

    It's not hard though since you already have Express installed.

    Here's a bare-bones node/express setup:

    var accountSid = process.env.TWILIO_ACCOUNT_SID;
    var authToken = process.env.TWILIO_AUTH_TOKEN;
    var client = require('twilio')(accountSid, authToken);
    
    const express = require('express')
    const app = express()
    
    app.post('/api', function (req, res) { 
        client.messages.create({
            to: "+1...",
            from: "+1...",
            body: "Testing, testing, testing"
        }).then((messsage) => {
            console.log(message.sid)
            res.send('done!', message.sid )
        });
    })
    
    app.listen(8000, function () {
    console.log('Example app listening on port 8000!')
    })
    

    Now you should be able to access it with something like:

    $.ajax({
    url: "http://localhost:8000/api",
    // etc.
     })
    
    评论

报告相同问题?