gpt4 book ai didi

node.js - 如何使用 Node https 请求发送 twilio 短信

转载 作者:太空宇宙 更新时间:2023-11-03 23:50:02 25 4
gpt4 key购买 nike

我正在尝试使用nodejs https模块在没有twilio sdk的情况下发送短信,但是twilio post api不断响应此错误“400,错误请求”,这意味着我可能没有以正确的方式制作请求。我遵循了 nodejs 文档 https 示例,还有 twilio 的示例。我也尝试过发出curl post 请求,它工作得很好。我哪里弄错了。这是我的代码

// Send an SMS message via Twilio
helpers.sendTwilioSms = (phone, message, callback) => {
// validate parameters
phone =
typeof phone == "string" && phone.trim().length == 10
? phone.trim().length
: false;
message =
typeof message == "string" &&
message.trim().length > 0 &&
message.trim().length <= 1600
? message.trim()
: false;

if (phone && message) {
// Configure the request payload
const payload = {
from: config.twilio.fromPhone,
to: `+234${phone}`,
body: message
};

// stringify payload using querystring module instead of JSON.stringify because the reqeust we'll be sending is not of application/json but 'application/x-www-form-urlencoded' form content-type as specified by Twilio
const stringPayload = querystring.stringify(payload);

// Configure the request details
var requestDetails = {
hostname: "api.twilio.com",
method: "POST",
path: `/2010-04-01/Accounts/${config.twilio.accountSid}/Messages.json`,
auth: `${config.twilio.accountSid}:${config.twilio.authToken}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(stringPayload)
}
};

// Instantiate the request
const req = https.request(requestDetails, res => {
// grab the status of the sent request
const status = res.statusCode;
console.log([
`(sendTwilioSms) making https post request`,
`(sendTwilioSms) response completed: ${res.complete}`,
`(sendTwilioSms) response statusCode: ${res.statusCode}`,
{ "(sendTwilioSms) response headers:": res.headers },
{ "(sendTwilioSms) response body:": res.body }
]);
// callback successfully if the request went through
if (status == 200 || status == 201) {
callback(false);
} else {
callback(500, {
Error: `Status code returned was ${status}: ${res.statusMessage}`
});
}
});

// Alert the user as to a change in their check status
workers.alertUserToStatusChange = newCheckData => {
const message = `Alert: Your check for ${newCheckData.method.toUpperCase()} ${
newCheckData.protocol
}://${newCheckData.url} is currently ${newCheckData.state}`;
helpers.sendTwilioSms(newCheckData.userPhone, message, err => {
if (!err) {
console.log(
"Success: User was aterted to a status change in their check, via sms: ",
msg
);
} else {
console.log(
"Error: Could not send sms alert to user who add a state change in their check"
);
}
});

这是回应:

    [
'(workers) making check request',
'(workers) check response completed: false',
'(workers) check response statusCode: 200'
]
logging to file succeeded
Check outcome has not changed no alert needed
[
'(sendTwilioSms) making https post request',
'(sendTwilioSms) response completed: false',
'(sendTwilioSms) response statusCode: 400',
{
'(sendTwilioSms) response headers:': {
date: 'Fri, 17 Jan 2020 09:49:39 GMT',
'content-type': 'application/json',
'content-length': '127',
connection: 'close',
'twilio-request-id': 'RQ7ee0b52d100c4ac997222f235e760fb7',
'twilio-request-duration': '0.025',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Accept, Authorization, Content-Type, If-Match, '
+
'If-Modified-Since, If-None-Match, ' +
'If-Unmodified-Since',
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
'access-control-expose-headers': 'ETag',
'access-control-allow-credentials': 'true',
'x-powered-by': 'AT-5000',
'x-shenanigans': 'none',
'x-home-region': 'us1',
'x-api-domain': 'api.twilio.com',
'strict-transport-security': 'max-age=31536000'
}
},
{ '(sendTwilioSms) response body:': undefined }
]
Error: Could not send sms alert to user who add a state change in their check

最佳答案

尝试这样的事情:

// authentication
var authenticationHeader = "Basic "
+ new Buffer(config.twilio.accountSid
+ ":"
+ config.twilio.authToken).toString("base64");

// Configure the request details
var requestDetails = {
host: "api.twilio.com",
port: 443,
method: "POST",
path: `/2010-04-01/Accounts/${config.twilio.accountSid}/Messages.json`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(stringPayload),
"Authorization": authenticationHeader
}
};

还有这个:

// Instantiate the request
const req = https.request(requestDetails, res => {
// grab the status of the sent request
const status = res.statusCode;

res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
callback(null, body);
});

// callback successfully if the request went through
if (status == 200 || status == 201) {
callback(false);
} else {
callback(500, {
Error: `Status code returned was ${status}: ${res.statusMessage}`
});
}
});
<小时/>

我希望它能起作用,我还没有测试过。如果它不让我知道,我会尝试并发布完整的测试代码。

关于node.js - 如何使用 Node https 请求发送 twilio 短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59785232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com