I'm trying to write a small node.js project to interface to a SMS gateway. (Cpsms.dk) They have a pretty straight forward API, but i'm quite new to node.js.
The folowing CURL function is working perfect:
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"
I'm trying to implement the same function in node.js (to be used with Firebase Cloud Function later, but right now just running locally.)
My code so far:
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);
});
But i'm getting a "404 Not Found", which i'm pretty sure is related to the Authorization. Can anyone help me?
1 Answer 1
404 means "not found", which has nothing to do with Authorization, the API endpoint was just not found, which has probably to do with the fact that in your cURL request you used POST, and in your node app you used no method, which means that request automatically uses the GET method. Try to either add method: 'POST' to your options or instead of request(options, callback) use request.post(options, callback).
To add your data, which already seems to be JSON, just add json: data to your options.
Since the request module is deprecated (see here: 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)
To use axios (or anything else) just install the package with npm, require it and look up their docs to use it: (axios) https://github.com/axios/axios or https://www.npmjs.com/package/axios