Search code examples
javascriptnode.jsrestopenfirenode-rest-client

How to create user in openfire using restapi in nodeJs application?


This is my function in NodeJs app which I am using to create user in openfire.

var createUser = function(objToSave, callback) {
    const options = {
        method: 'POST',
        uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
        headers: {
            'User-Agent': 'Request-Promise',
            'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        data: objToSave
    }
    request(options)
        .then(function(response) {
            callback(null, response);
        })
        .catch(function(error) {
            // Deal with the error
            console.log(error);
            callback(error);
        });
};

the objToSave is a json object contains username and password.

{
  "Username": "gabbar",
  "Password": "gabbar@123"
}  

when i run this function i am getting the following error..

{
  "statusCode": 400,
  "error": "Bad Request"
}

I configured my secret-key properly and domain name is localhost://9090, can anybody tell me what I am doing wrong ? thanks in advance.


Solution

  • I find out that problem was with request-promise. it was not properly sending data in the required format. so Instead of that now I am using different module minimal-request-promise. and It worked like charm for me. After using that, my code looks something like this.

    var requestPromise = require('minimal-request-promise');
    
    var createUser = function(objToSave, callback) {
        const options = {
            headers: {
                'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(objToSave)
        };
        requestPromise.post('http://localhost:9090/plugins/restapi/v1/users', options)
            .then(function(response) {
                callback(null, response);
            })
            .catch(function(error) {
                // Deal with the error
                console.log(options);
                console.log(error);
                callback(error);
            });
    };