当我的Alexa技能调用了Intent时,我想发送POST请求到Twilio。在测试代码时,没有错误,但是请求似乎没有通过。在Postman工程中测试POST请求。
function postToTwilio() {
var http = require("https");
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(postData);
req.end();
}
答案 0 :(得分:1)
首先,请求是异步调用,因此您需要让alexa等待响应。
为此,您需要使用async await进程并使用promises。
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
function get(options) {
return new Promise(((resolve, reject) => {
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
if (response.statusCode < 200 || response.statusCode >= 300) {
return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
}
response.on('data', (chunk) => {
returnData += chunk;
});
response.on('end', () => {
resolve(JSON.parse(returnData));
});
response.on('error', (error) => {
reject(error);
});
});
request.write(postData)
request.end();
}));
}
然后,当您调用此get函数时:
let response = await get(options)
我还没有进行整体测试,但这是基本框架。
让我知道是否可行。