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.
     })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法