[英]Convert request.js to axios (Vonage api)
我正在使用 Vonage api 进行信使项目。 此代码运行良好,但我尝试将其转换为 axios 而不是 require.js
var request = require("request");
const data = JSON.stringify({
from: { type: "messenger", id: process.env.BOT_ID },
to: { type: "messenger", id: process.env.USER_ID },
message: {
content: {
type: "text",
text: "Hi There!",
},
},
});
var options = {
url: "https://messages-sandbox.nexmo.com/v0.1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: data,
auth: {
user: process.env.API_KEY,
pass: process.env.API_SECRET_KEY,
},
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
这是具有相同要求的 axios 版本:
axios({
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: {
from: { type: "messenger", id: process.env.BOT_ID },
to: { type: "messenger", id: process.env.USER_ID },
message: {
content: {
type: "text",
text:
"Hi There!"
},
},
},
auth: {
user: process.env.API_KEY,
pass: process.env.API_SECRET_KEY,
},
url: "https://messages-sandbox.nexmo.com/v0.1/messages",
});
它不起作用。 我也试过
设置正文数据的 axios 属性是“数据”,而不是“正文”。 这让我以前很困惑。 请尝试以下使用控制台日志记录来检查是否发送了正确的请求:
axios({
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
data: {
from: { type: "messenger", id: process.env.BOT_ID },
to: { type: "messenger", id: process.env.USER_ID },
message: {
content: {
type: "text",
text:
"Hi There!"
},
},
},
auth: {
user: process.env.API_KEY,
pass: process.env.API_SECRET_KEY,
},
url: "https://messages-sandbox.nexmo.com/v0.1/messages",
});
Vonage 支持向我发送了此代码并且它有效(没有正文或数据)
axios
.post(
"https://messages-sandbox.nexmo.com/v0.1/messages",
{
from: { type: "messenger", id: "107083064136738" },
to: { type: "messenger", id: "3958866477502819" },
message: {
content: {
type: "text",
text: "You should havee ",
},
},
},
{
auth: {
username: "5aa06d41",
password: "FMqffmop1GB64X58",
},
}
)
.then(function (response) {
console.log("Status: " + response.status);
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.