Mustafa bw
Mustafa bw

Reputation: 1462

node - Invalid uri error in npm-request

var request = require('request');
var options = {                
    url: 'https://connect1on1.com/api/web/index.php/v1/message/save-message',
    method:'POST',
    body:JSON.stringify({"id": data.user_id, "message": data.message}),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': data.length,
        'Access-Token': data.access_token
    }
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(error);
        //  var info = JSON.parse(response);
    }
}
request(options, callback);

I have add npm-request package for api call.

I have set all params in options and pass second option as callback function.

but i am getting this error. "Invalid Uri"

My question is how can i call secure https url in npm-request

Upvotes: 2

Views: 4445

Answers (1)

Ziki
Ziki

Reputation: 1440

The request package should handle also HTTPS requests.

Try to change the key url in your options to uri

P.S. I use node HTTPS library, and it works, maybe consider use it also.

Here's an ex. with NodeJS HTTPS library in EcmaScript 2015:

let https = require(`https`);
let postData = new Buffer(JSON.stringify({"id": data.user_id, "message": data.message}));
let options = {
    hostname: "www.connect1on1.com",
    path: "/api/web/index.php/v1/message/save-message",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": postData.length,
        "Access-Token": data.access_token
    }
};

let req = https.request(options, (res) => {
    if (res.statusCode !== 200) {
        throw Error(`request statusCode is: ${res.statusCode}`);
    }
    res.setEncoding(`utf8`);
    res.on(`data`, chunk => console.log(chunk));
});

req.on(`error`, (e) => {
    throw Error(`problem with request: ${e.message}`);
});

req.write(postData);
req.end();

Upvotes: 3

Related Questions