Execute second function after first function - REST - javascript

If the first REST function execute with sucess, the second it will be execute with the parameters of the first function, in the case return: sessionid and I save the value inside variable sessionid
Both functions are REST call within the same .js file.
In the case I trying:
My restApiCall.js file:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // I try execute, but just the first execute if I type inside Prompt command: node restApiCall
}
});
// this is the second function I want execute after the first sucess
function openRequest(sessionid, numberOrigin){
var client = new Client();
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(response);
});
}
Thanks advance.

In the case the problem is new Client(); because the client have definied with line 2 and dont necessary declare again.
I use this code and works fine.
var Client = require('./lib/node-rest-client').Client;
var client = new Client(); //defined
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}

Related

Trying to dynamically set .find() parameters from client input - mongodb:Atlas

I am trying to use data from the client, which they would type into an input box. The idea is to use this for finding in my database to pull the data with the same username. on my Mongo DB:Atlas collection.
So its to use it like this to get the names from the database, .find({"username": request.body})
However, I keep getting the error "CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1" on my terminal.
But when I try to hard code it onto the .find({"username": "name"), it works fine. Does anyone have any ideas?
**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
Actually, you're passing the object {username : "value"} to the find method. You need to pass the string.
app.post('/database', (request,response) => {
const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

send response from nodejs express to angular app

I am calling an api of sending OTP from my nodejs app. I need to send the response of that OTP Api to the angular app.
my api service on angular look like this:
sendOtp(params): Observable<any> {
return this.apiService.post("/user/send-otp", params)
}
my router on express app look like this
this.router.post("/user/send-otp", userController.sendOtpMessage);
and the code inside userController look like this.
static sendOtpMessage(req, res ,next) {
const phone = req.body.phone;
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.msg91.com",
"port": null,
"path": `/api/v5/otp?mobile=${phone}`,
"headers": {
"content-type": "application/json"
}
};
var callOtpApi = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// I need to send this data in response to my angular app ==>> body.toString()
});
});
callOtpApi.write();
callOtpApi.end();
}
OTP Api ref document: https://docs.msg91.com/p/tf9GTextN/e/B1NUt3C8MY/MSG91
It seems that the code above is missing the res.send() to return the data from server. Could you please try with this?
static sendOtpMessage(req, res ,next) {
const serverRes = res;
// Rest of your code
...
var callOtpApi = http.request(options, function (res) {
// Rest of your code
...
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// Return data to client
serverRes.send(body.toString());
});
// Rest of your code
...
});
}
You can call the msg91 api using axios
const axios = require('axios');
async function sendOtpTOUser(phone) {
const template = "template _id";
const apiKey = "api_key";
const sendotp = "https://api.msg91.com/api/v5/otp?template_id="+template+"&mobile="+phone+"&authkey="+apiKey;
let request_options1 = {
method: 'get',
url: sendotp
};
let otpResponse = await axios(request_options1);
console.log(otpResponse.data)
return otpResponse.data;
}
it will return the object as
{ request_id: '3166686e7867313634383535', type: 'success' }

how to read file contents using axios and a file URL? [duplicate]

I'm using axios on server side.
I want to download big files .. technically this should be used with byte-ranges
Does axios handle the byte-range request so that the callback function is only called when all the response is ready
If 1 is not true, should I handle data chunks myself ?
In the code below :
axios({
url: params.url,
method: 'GET',
responseType: 'stream' // important
}).then(function (response) {
logger.debug('__download() : done!')
let contentType = response.headers['content-type']
let contentLength = response.headers['content-length']
var writer = new streams.WritableStream()
response.data.pipe(writer)
// ....
})
Am I supposed to wait for something like response.on('end')?
The purpose of what I'm doing is to get the size of the buffer (which I could get by writer.getBuffer())
Thanks for any hint !
I found out that to download the stream, in memory in my case, I had to wait for the event on my writer (writer.on('finished',cb) vs response.on('end', cb )) (not sure if there is something like response.on('end'))...
var stream = require('stream');
var util = require('util');
var Writable = stream.Writable;
function MemoryStream(options) {
if (!(this instanceof MemoryStream)) {
return new MemoryStream(options);
}
Writable.call(this, options); // init super
}
util.inherits(MemoryStream, Writable);
MemoryStream.prototype._write = function (chunk, enc, cb) {
var buffer = (Buffer.isBuffer(chunk)) ?
chunk :
Buffer.alloc(chunk, enc);
if (Buffer.isBuffer(this.memStore)) {
this.memStore = Buffer.concat([this.memStore, buffer]);
} else {
this.memStore = buffer
}
cb();
};
MemoryStream.prototype.toBuffer = function () {
return this.memStore
};
module.exports = MemoryStream
and then in my download function :
axios({
url: params.url,
method: 'GET',
responseType: 'stream' // important
}).then(function (response) {
logger.debug('__download() : done!')
let contentType = response.headers['content-type']
let contentLength = response.headers['content-length']
var writer = new MemoryStream()
response.data.pipe(writer)
writer.on('finish', function () {
var b = writer.toBuffer()
let computedContentLength = b.byteLength
if (!contentLength) { contentLength = computedContentLength }
return callback(null, { 'foo':'bar'})
});
})

How to use fetch to send a variable to a GET request?

I am having an issue with using fetch to send an id which is then sent to a get request in the backend which performs a function.
The aim of the function is to delete the element from the JSON file which is entered into the input box in the front end.
However, when I do this, I get an error saying the route for the function is not found:
GET http://localhost:3000/delete 404 (Not Found)
This is the code for the /delete route:
app.get('/delete/:id', function (req, res) {
var id = req.params.id;
for (var i = 0; i < tasksArray.length; i++) {
if(tasksArray[i].id == id) {
tasksArray.splice(i, 1);
}
}
res.json(tasksArray);
var json = JSON.stringify(tasksArray);
fs.writeFileSync("toDoList.json", json);
});
This is the code for the front end with fetch:
function deleteElement() {
var id = document.getElementById("deleteId").value;
var url = "http://localhost:3000/delete";
fetch(url, {
method: 'GET',
url: `/delete/${id}`,
headers: {
'Content-Type': 'application/json'
}
});
}
Any help is appreciated.
You were not using id in the url.
function deleteElement() {
var id = document.getElementById("deleteId").value;
var url = "http://localhost:3000/delete/" + id;
fetch(url, {
// removed url as it's defined in fetch's first arguments.
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
}

Unable to paginate on a callback function

I'm trying to paginate on a call to callback function but getting an error over second call
my function does:
let content = ''
let size = 100
let from = 1
function result(size, from, callback) {
api.performRequest('/myContents', 'GET', {
pageSize: size,
startFrom: from,
filter:'NOT contents:[* TO *]',
}, function (data) {
content += JSON.stringify(data)
callback()
})
}
function logContent() {
const parsed = JSON.parse(content)
console.log('content length: ', parsed.body.length)
if (parsed.body.length === size) {
calculate(size, from + size)
}
}
function calculate(size, from) {
result(size, from, logContent)
}
calculate(size, from)
on the first call the console returns
content length: 100
on the second call I get all my json chunk on the logs and an error
Unexpected token { in JSON at position 32847
I think it has to do with the callback and something happening before the function finishes, but I'm unable to see what I'm doing wrong here
the function performRequest just does an http get and returns a json chunk
export function performRequest(endpoint, method, data, callback) {
const headers = {
Authorization: auth,
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Expose-Headers': 'Location,ETag',
}
let options = {
host: host,
port: port,
path: endpoint,
headers: headers,
}
if (method === 'GET') {
endpoint += '?' + queryString.stringify(data)
const additionalOptions = {
path: endpoint,
}
options = _.merge(options, additionalOptions)
}
return http.get(options, function (response) {
// Continuously update stream with data
let body = ''
response.on('data', function (d) {
body += d
})
response.on('end', function () {
// Data reception is done
const parsed = JSON.parse(body)
callback({
totalCount: parsed.totalCount,
body: parsed.content,
})
})
})
}
Your first call is going to be fine, because your content is empty at first. So, during the first call:
content = '' --> content = '{...}'
And your second call :
content = '{...}' --> content = '{...}{...}'
Thus the error :
Unexpected token { in JSON at position 32847
You need to put every objects in an array, or even in another object if you want it to work. You can create an array and push every element into it at every call.

Categories

Resources