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

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.

I think the options you provided needs JSON.stringify object before send it
The modified options is as below
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: JSON.stringify(objToSave)
}

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);
});
};

Related

use a specific value from JSON response from GET request via fetch --> to a POST request

the main goal here is to use the part of the response, in the 2nd POST requset.
Let me explain -
given the following endpoint:
https://www.example.com/Applications/?api-version=1&_cacheToken=1675420688869
the response from sending a GET request to the endpoint is :
{"field1":"","Items":[{"Name":"app:\/appname","field2":"appnumber","field3":"appvers","Status":"Ready","Parameters":[],"health":"Ok","kind":"numbers","ids":{"id":[]},"met":{"met1":{}},"Id":"1"}]}
I would like to use only the value of "appname".
hence i'm using it as follows -
---SNIP---
...
.then(data => {
const appname = data.Items[0].Name;
const appname_updated = appname.replace('app:/', '');
...
---SNIP---
I would like to use it with a second fetch request, but this time in a form of POST (in the endpoint itself and in the body):
return fetch('https://www.example.com/deploy/'+appname_updated+'/?api-version=1', {
method: 'POST',
headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json; charset=utf-8' },
mode: 'no-cors',
body: JSON.stringify({
appname: appname_updated,
field1: "blah"
})
});
})
How this can possible be done ? so the first GET will be sent, receieve 200 ok,
and once it got the 200 status, the POST should send right after with the proper
values populated.
No matter what i've tried so far, nothing seems to be send the second POST rquest.
(I've tried it with asyc/wait etc.)
----- update ----
this is the full code -
<script>
const firstUrl = "https://example.com/Applications/?api-version=1";
const secondUrl = "https://example.com/deploy/";
async function fetchData() {
try {
const response = await fetch(firstUrl, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json; charset=utf-8'
}
});
if (response.status === 200) {
const data = await response.json();
const appname_updated = data.Items[0].Id;
const secondResponse = await fetch(secondUrl + appname_updated + '/?api-version=1', {
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify({
appname: appname_updated,
...rest of JSON
})
});
if (secondResponse.status === 200) {
console.log("POST request successful");
} else {
console.error("Error with POST request");
}
} else {
console.error("Error with GET request");
}
} catch (error) {
console.error("Error with fetch: ", error);
}
}
fetchData();
</script>
Thanks
'no-cors' tells fetch to fail silently if you try to do anything which requires permission from CORS.
Making a cross-origin request with 'Content-Type': 'application/json; charset=utf-8' requires permission from CORS.
Don't use 'no-cors'.

How can i get the cookies of the first request and use it in the next one?

I have a problem with using axios in javascript.
I want to access my docuware to get the current Booking status. Docuware uses Cookie Authentication, so I need to get the cookies .DWPLATFORMAUTH, dwingressplatform and DWPLATFORMBROWSERID and send it in the next request.
Here is my code:
const axios = require('axios');
var querystring = require('querystring');
console.log(geta('mysecretuser', 'mysecretpw', mysecretdocid));
function geta(UserName, Password, docId) {
return axios.post('https://myorga.docuware.cloud/Docuware/Platform/Account/LogOn',
querystring.stringify({
UserName: UserName,
Password: Password
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Connection': 'keep-alive',
}
}).then(response => {
axios.get("https://myorga.docuware.cloud/DocuWare/Platform/FileCabinets/FILECABINETID/Documents/" + docId, { withCredentials: true, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive',
}}).then(response1 => {
const jsonObject = response1.data;
console.log(jsonObject.VERANSTALTUNG)
console.log(jsonObject.ANMELDUNGEN)
return 0;
})
.catch(error => {
console.log(error);
});
}
).catch(error => {
console.log(error.code)
return -1;
});
}
I have tried to fix this problem with inserting withCredentials: true when creating the second request. It didn't work. Also I have tried to set the Connection header to keep-alive, but it also didn't change.

How to get the response JSON from API call

I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})
This is the API call I am calling.
app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;
var user = req.params.user;
var password = req.query.password;
console.log(user, password);
var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});
When I do console.log(res) in the fetch call, this is what is printed:
Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response
When I visit the website, the output is:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is what I want.
In general, this is how you return the response body from the Promise.
fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then‌​(data=> {
console.log(data);
})
Try this way to parse the response:
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then(async (res) => {
const raw = await res.text();
const parsed = raw ? JSON.parse(raw) : { success: res.ok };
console.log(parsed);
})
In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.
for you to get the JSON body content from the response, you need to use json()
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
const jsonData = res.json();
console.log(jsonData);
})
try this
fetch(${baseUrl}/api/user/${user}?password=${password},{
method:'GET',
headers: {
'Accept': 'application/json',
'Content-Type':
'application/json',
}}) .then(async(response ) => {
await response.json()
})

Why is angularjs url encoding my POST params?

Here is the rest client in our service:
self.headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
};
self.loginClient = $resource(self.baseUrl + '/users/login', {
userId: '#userId',
password: '#password'
}, {
save: {
method: 'POST',
headers: self.headers
}
});
I call it like this -
AuthService.loginClient.save({
userId: self.user.email,
password: self.user.password
}).$promise.then(function (res) {
// do stuff
})
The URL path that the browser is hitting looks like this:
/users/login?password=XXXXXX&rememberMe=false&userId=XXXXXX
Can anyone tell what I have wrong here that is leading to the url encoding of my POST params? Please let me know what other info I can provide.
Just pass the data to the action method.change the service like this
self.headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
};
self.loginClient = $resource(self.baseUrl + '/users/login', {
save: {
method: 'POST',
headers: self.headers
}
});
call it like this
AuthService.loginClient.save({},{
userId: self.user.email,
password: self.user.password
})

How to re-do a code part if there is an error without rewriting it ?

In my code I make some API calls and sometimes 1 of them return an error but if I re-do it just after it works (I don't really know what's wrong maybe the JSON that I post is not finish or I don't know...)
So to make that I have coded:
HTTP.call("POST", "http://localhost:3000/api/dashboards/db", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': APIKEY,
},
data: {
dashboard: dataJSON,
overwrite: true
}
},
function(error, result) {
if (!error) {
console.error("result post dataJSON --------------------OK------------")
} else {
console.log("error post dataJSON --------------------KO------------")
HTTP.call("POST", "http://localhost:3000/api/dashboards/db", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': APIKEY,
},
data: {
dashboard: dataJSON,
overwrite: true
}
},
function(error, result) {
if (!error) {
console.error("result post dataJSON at the 2nd time --------------------OK------------")
} else {
console.log("error post dataJSON at the 2nd time --------------------KO------------")
}
});
}
But it's very ugly to make something like this I think so is it a way to recall the code's part when there is an error ?
Well, my first suggestion is to understand why the call fails the first time around and see if you can fix it.
Excluding that, it depends a bit on you plan to use the data and such, but, for example, you could isolate the HTTP call in a function, and recall the function with the same arguments.
function callAPIwithData(myData) {
HTTP.call("POST", "http://localhost:3000/api/dashboards/db", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': APIKEY,
},
data: myData
},
function(error, result) {
if (!error) {
console.error("OK: result post dataJSON")
} else {
console.log("KO: error post dataJSON")
console.log("retrying ...")
callAPIWithData(myData);
}
});
}
of course this will need a set of checks and balances so it won't get stuck re-trying to infinity in casa there's something else broken, but you get the idea.

Categories