Fetch api not posting data to backend server - azure

I am using cognitive service by azure which I am using Face API, In frontend the user will take picture then will call the API to check if face detected or not after that face id will be added using Add Face under FaceList as in azure documentation, after that I want to update column in database if face added successfully, here i am calling a function called senddata() which will use fetch API to send data to backend server then in server the database column will be updated, the problem is after face added successfully the senddata() function is not posting any data to backend server:
here is the code of taking picture:
const takePicture = async () => {
if (camera) {
const data = await camera.current.takePictureAsync({ quality: 0.25, base64: true });
const selfie_ab = base64ToArrayBuffer.decode(data.base64);
setTakingPic(true)
try {
const facedetect_instance_options = { ...base_instance_options };
facedetect_instance_options.headers['Content-Type'] = 'application/octet-stream';
const facedetect_instance = axios.create(facedetect_instance_options);
const facedetect_res = await facedetect_instance.post(
`/detect?returnFaceId=true&detectionModel=detection_02`,
selfie_ab
);
console.log("face detect res: ", facedetect_res.data);
if (facedetect_res.data.length) {
const add_face_instance_options = { ...base_instance_options };
add_face_instance_options.headers['Content-Type'] = 'application/octet-stream';
const add_face_instance = axios.create(add_face_instance_options);
const addface_res = await add_face_instance.post(
`/facelists/${facelist_id}/persistedFaces`, selfie_ab
);
if (addface_res.data.persistedFaceId.length) {
const status = "on hold";
const faceid = addface_res.data.persistedFaceId;
senddata(status, faceid)
console.log("Face add and send for approval: ", addface_res.data.persistedFaceId);
} else {
Alert.alert("error", "something went wrong");
}
} else {
Alert.alert("error", "Detection failure. Please make sure there is sufficient light when taking a selfie");
}
} catch (err) {
console.log("err: ", err);
}
}
};
here the senddata() function:
const senddata = (status, faceid) => {
console.log(status)
console.log(faceid)
fetch('http://*********/users/updateRegStatus', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
status: status,
faceid: faceid
})
})
.then((response) => response.json())
.then((res) => {
if (res.success === true) {
alert(res.message);
navigation.navigate('dashboard')
}
else {
alert(res.message);
}
})
}
and the following code form the backend which for updating the database:
router.post('/updateRegStatus', function (req, res, next) {
var status = req.body.status;
var faceid = req.body.faceid;
connection.query("INSERT INTO face_status (status,faceid) VALUES (?,?) ", [status, faceid], function (err, row) {
if (err) {
console.log(err);
} else {
res.send({ 'success': true, 'message': 'Your face details sent for approval' });
}
});
});
pleaser help me

Related

Cannot get data from backend while updating

Here's the code in react that I am using to get the data from database.
const getData = async (e) => {
const res = await fetch(`${process.env.REACT_APP_BASE_URL}/edit/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
console.log(data);
if (res.status === 422 || !data) {
console.log("Error");
} else {
setValues(data);
console.log("Data Edited successfully");
}
};
useEffect(() => {
getData();
}, []);
Here's the patch request
router.patch("/edit/:id", async (req, res) => {
try {
const { id } = req.params;
const updateUser = await Crud.findByIdAndUpdate(id, req.body, {
new: true,
});
console.log(updateUser);
res.status(201).json(updateUser);
} catch {
res.status(422).json(error);
}
});
I want to update the data in my application but I cannot get the data from the database. So can anyone tell what the problem is
From frontend, you are calling GET request and from your backend, you're receiving as a patch how it works pls do the same method on both hands

In React 18, when I am sending data to nodejs server, it is sending two request and receiving two response from server

This is the front-end code which is used for sending access token to server site.
useEffect(() => {
const getProducts = async () => {
try {
const url = `http://localhost:5000/product?email=${user.email}`
const { data } = await axios.get(url, {
headers: {
authorization: localStorage.getItem('accessToken')
}
});
setProducts(data);
} catch (err) {
const status = err.response.status;
if (status === 401 || status === 403) {
signOut(auth);
navigate('/login');
localStorage.removeItem('accessToken')
toast.error(err.response?.data?.message);
}
}
}
getProducts();
}, [user.email]);
This is server site express code for response. Why every time it is receiving two request and sending two response?
app.get('/product', verifyToken, async (req, res) => {
const decoded = req.decoded?.email;
const queryEmail = req.query?.email;
if (decoded === queryEmail) {
const query = { email: queryEmail };
const cursor = medicineCollection.find(query);
const products = await cursor.toArray();
res.send(products);
} else {
res.status(403).send({ message: "Forbidden Access" })
}
})
Maybe you take user.email in a state which is updating somehow so that's why useEffect is calling again and giving you twice response.

Can not get the data in response from Azure httpTriggered Function in NodeJS

I am creating a REST API service using Azure Function in nodeJs. The function is reading some data from Azure SQL and I want it to be returned. I am using tedious package to connect to Azure SQL Database.
const { Connection, Request } = require("tedious");
var data = [];
console.log("0." + data);
const config = {
authentication: {
options: {
userName: "------", // update me
password: "--------" // update me
},
type: "default"
},
server: "----.database.windows.net", // update me
options: {
database: "---", //update me
encrypt: true
}
};
module.exports = async function (context, req, resp) {
const connection = new Connection(config);
context.bindings.response = { status: 201, body: {"time": new Date().getUTCMinutes(), "data": data} };
connection.on("connect", err => {
if (err) {
console.error(err.message);
} else {
queryDatabase(context);
}
});
connection.connect();
//context.bindings.response = { status: 201, body: JSON.stringify(data) };
function queryDatabase(context) {
console.log("Reading rows from the Table...");
// Read all rows from table
const request = new Request(
`SELECT FirstName, LastName FROM Persons`,
(err, rowCount, data) => {
if (err ) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
}
}
);
request.on("row", columns => {
var row = {};
columns.forEach(column => {
row[column.metadata.colName] = column.value;
console.log("%s\t%s", column.metadata.colName, column.value);
data.push(row);
});
});
connection.execSql(request);
}
}
I can read data from Azure SQL Database and the console.log is printing data in the console.
console.log("%s\t%s", column.metadata.colName, column.value);
But while I am trying to bind the data to response, it always shows blank.
{
"time": 52,
"data": []
}
How and where to bind the context.bindings.response?
If I’ve understood you correctly, try this approach ...
// Construct response
const responseJSON = {
"name": "Some name",
"sport": "Some sport",
"message": "Some message",
"success": true
}
context.res = {
// status: 200, /* Defaults to 200 */
body: responseJSON,
contentType: 'application/json'
};

Request is not giving response if i use it with await inside a try block?

I have a piece of code where I am trying to get the response from Okta to a variable and return it to the calling service.
I am trying to use async also along with this. But this is keep getting failed like response from the post request is never coming to the try block. How can I achive this?
exports.oktaLogin = async function (request) {
//const transaction = await sequelizedb.transaction();
logger.info('UserServices.oktaLogin',request);
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
let username = request.username;
let password = request.password;
let dataString = "{\"username\": \""+username+"\", \"password\": \""+password+"\", \"options\": { \"multiOptionalFactorEnroll\": true, \"warnBeforePasswordExpired\": true } }";
//console.log(dataString);
options = {
url: constants.OKTA_URL,
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
//console.log('Called Call back');
if (!error && response.statusCode == 200) {
console.log('Inside call back');
console.log(body);
if(body){
return { success: true, user: body };
}else{
return false;
}
}else{
return { success: false, error: 'No User Found' };
}
}
try {
let some = await reqcall(options, callback);
console.log('--------------------------')
console.log(some);
} catch (error) {
return { success: false, error: 'No User Found' };
}
};
How do I make the call back to work with async?
Also is there a possibility to use this With axios?
with axios, I would write something like
const axios = require('axios');
exports.oktaLogin = async (req) => {
const { username, password } = req;
const payload = {
username, password,
options: { multiOptionalFactorEnroll: true, warnBeforePasswordExpired: true }
};
try {
const res = await axios.post(constants.OKTA_URL, payload);
return {
success: true,
user: res.data
};
} catch (err) {
return {
success: false,
error: 'No User Found',
message: err.message
};
}
};
that matchs what you have, but I would do a bit more, for example, I would not rely on success but would send back an error for example
const axios = require('axios');
exports.oktaLogin = async (username, password) => {
const payload = {
username, password,
options: { multiOptionalFactorEnroll: true, warnBeforePasswordExpired: true }
};
return await axios.post(constants.OKTA_URL, payload);
};
the function will now return what it should, and you know exactly what parameters such function needs (username and password, and not the ExpressJs full request object as you don't need and looking at the function signature it's hard to understand what you will need that object to have)
then I'd use as
app.post('/login', async (req, res) => {
const { username, password } = req;
if (!isUsernameValid(username) || !isPasswordValid(username)) {
res.status(400).json({ error: 'Invalid input' });
}
try {
const login = await oktaLogin(username, password);
res.json({
user: login.data
});
} catch (err) {
res.status(400).json({ error: err.message });
}
});
where, just as an example
const isPasswordValid = password => password.length > 8;
const isUsernameValid = username => username.length > 3;
you could read a bit more about axios and create your own javascript file to test what it returns and what it gets, a simple file with
const axios = require('axios');
(async() => {
const HOST = 'https://jsonplaceholder.typicode.com';
const api = axios.create({
baseURL: HOST
});
// get first TODO
let res = await api.get('/todos/1');
console.log(res.status, JSON.stringify(res.data, null, 2));
// create new TODO
res = await api.post('/todos', {
title: 'test title',
body: 'test body'
});
const newId = res.data.id;
console.log(res.status, JSON.stringify(res.data, null, 2));
// delete last todo
res = await api.delete(`/todos/${newId}`);
console.log(res.status, JSON.stringify(res.data, null, 2));
})();
and try other calls, use a REST service for example, like https://jsonplaceholder.typicode.com/ so you can use other HTTP verbs
and run as node ./index.js (if the new file is index.js

Node JS serverless rest API lambda function that first performs GET request and then POST if condition is met

I'm new to NodeJS and I'm supposed to write a serverless rest API for a online store (school project). The team I'm in is responsible of the orders customers place. To be able to place the order there has to be enough quantity in inventory (another API), so we need to check quantity in inventory using GET before we store the order in a database using POST. How should we go about this? This is what I have tried, but I end up getting timeout. The code below is based on this example: aws-node-rest-api-with-dynamodb for me to get the hang of NodeJS and serverless.
.yml file
functions:
create:
handler: todos/test.f
events:
- http:
path: todos
method: post
cors: true
test.js
const create = require("./create.js");
exports.f = function() {
const https = require('https');
https.get('url goes here', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
var str = String(data);
console.log("Check: " + (str.trim() == "OK"))
create.c(); //also tried create.create();
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
create.js
'use strict';
const uuid = require('uuid');
const dynamodb = require('./dynamodb');
exports.c = function (){
console.log("Fire!");
}
module.exports.create = (event, context, callback) => {
const timestamp = new Date().getTime();
const data = JSON.parse(event.body);
if (typeof data.text !== 'string') {
console.error('Validation Failed');
callback(null, {
statusCode: 400,
headers: { 'Content-Type': 'text/plain' },
body: 'Couldn\'t create the todo item.',
});
return;
}
const params = {
TableName: 'todos',
Item: {
id: uuid.v1(),
text: data.text,
checked: false,
createdAt: timestamp,
updatedAt: timestamp,
},
};
// write the todo to the database
dynamodb.put(params, (error) => {
// handle potential errors
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
headers: { 'Content-Type': 'text/plain' },
body: 'Couldn\'t create the todo item.',
});
return;
}
// create a response
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
};
callback(null, response);
});
};
Any thoughts on how to get this to work?

Resources