我在发送短信后尝试从Twilio的JSON响应中获取sid
和date_created
,但它们始终为undefined
。
我还尝试了body.['sid']
和body.['date_created']
,但他们仍然没有返回正确的值。
const textMe = function sendSms() {
request.post(options, (err, resp, body) => {
if (err) {
console.log('error:', err);
} else {
console.log('statusCode:', resp.statusCode);
console.log('sid:', body.sid);
console.log('dateCreated:', body.date_created);
}
});
};
textMe();
statusCode: 201
sid: SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
dateCreated: Sat, 10 Jun 2017 14:55:14 +0000
statusCode: 201
sid: undefined
dateCreated: undefined
{"sid": "SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "date_created": "Sat, 10 Jun 2017 14:55:14 +0000", "date_updated": "Sat, 10 Jun 2017 14:55:14 +0000", "date_sent": null, "account_s
id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "to": "+xxxxxxxxxxxx", "from": "+xxxxxxxxxxxx", "messaging_service_sid": null, "body": "Sent from your Twilio trial account - Twilio Test using
Node.js and request.", "status": "queued", "num_segments": "1", "num_media": "0", "direction": "outbound-api", "api_version": "2010-04-01", "price": null, "price_unit": "USD", "error_cod
e": null, "error_message": null, "uri": "/2010-04-01/Accounts/xxxxxxxxxxxx/Messages/xxxxxxxxxxxx.json", "subresource_uris": {"media": "/2010-0
4-01/Accounts/xxxxxxxxxxxx/Messages/xxxxxxxxxxxx/Media.json"}}
编辑:
const textMe = function sendSms() {
request.post(options, (err, resp, body) => {
if (err) {
console.log('error:', err);
} else {
console.log('statusCode:', resp.statusCode);
console.log('sid:', JSON.parse(body).sid);
console.log('dateCreated:', JSON.parse(body).date_created);
}
});
};
textMe();
答案 0 :(得分:0)
你的身体仍然是字符串吗?如果是这样,您将需要JSON.parse(body)来访问JSON对象中的属性。