Node.js + 请求 POST 基本授权

Node.js + request POST Basic Authorization

我正在尝试编写一个小型 node.js 项目来连接到 SMS 网关。 (Cpsms.dk) 他们有一个非常简单的 API,但我对 node.js 很陌生。

以下 CURL 功能运行良好:

curl -X POST -H "Authorization: Basic MyApiKey" -d '
{
"to":"4512345678", "message": "This is the message text body", "from": "CPSMS"
}
' "https://api.cpsms.dk/v2/send"

我正在尝试在 node.js 中实现相同的功能(稍后与 Firebase Cloud Function 一起使用,但现在只是 运行 在本地。)

到目前为止我的代码:

const request = require('request');

const url = "https://api.cpsms.dk/v2/send";
const data =  '{"to":"4512345678", "message": "This is the message text body", "from": "CPSMS"}';
const auth = "Basic MyApiKey";

const options = {
  url : url,
  headers : {
      "Authorization" : auth
  },
};

request(options, function(err, res, body) {
    console.log(body);
});

但我收到“404 未找到”消息,我很确定这与授权有关。 谁能帮帮我?

404 表示“未找到”,这与授权无关,只是未找到 API 端点,这可能与您在 cURL 请求中使用 POST,并且在您的节点应用程序中您没有使用任何方法,这意味着该请求会自动使用 GET 方法。尝试将 method: 'POST' 添加到您的选项中,或者使用 request.post(options, callback).

代替 request(options, callback)

要添加您的数据,似乎已经是 JSON,只需将 json: data 添加到您的选项中。

由于请求模块已弃用(参见此处:https://github.com/request/request/issues/3142), I would recommend you use something else like axios or got (axios: https://www.npmjs.com/package/axios, got: https://www.npmjs.com/package/got

要使用 axios(或其他任何东西)只需使用 npm 安装包,需要它并查找他们的文档以使用它:(axios) https://github.com/axios/axios or https://www.npmjs.com/package/axios