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
Related
I have a router.get which calls another function, like this:
router.get("/", (req, res) => {
const data = especiaisTest.getEspeciais();
console.log(data);
});
The function which is calling is this one:
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
}
Whenever i call it, I just get console.logged an undefined.
I tried returning a value outside the db.query function, for example:
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
return 'hello'
}
And it will display the 'hello' in the console. How can I get the response.data out of the db.query in order to be able to show the data?
Question codes.
router.get("/", (req, res) => {
const data = especiaisTest.getEspeciais();
console.log(data);
});
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
}
Should be:
router.get("/", async (req, res) => {
const data = await especiaisTest.getEspeciais();
async function getEspeciais() {
return db.query(async (tokenResponse) => {
Then you will see something else rather than undefined.
If return undefined, the db.query method return nothing.
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.
I have my function that create requests to get recents tweets by a keyword (I'm using NodeJS), but I need to stop it after 10 tweets, how can I do that? From the twitter api doc I didn't find anything...
Here only mentions the limit but not how to set it
https://developer.twitter.com/en/docs/twitter-api/rate-limits
Here the code:
const rules = [{
value: //keyword
}]
function streamTweets() {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
}
})
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json)
} catch (error) {
}
})
}
(async () => {
let currentRules
try {
currentRules = await getRules()
await deleteRules(currentRules)
await setRules()
} catch (error) {
console.error(error)
process.exit(1)
}
streamTweets()
})()
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
I want to do make the same api call as made in this postman photo below :
postman
I have already tried the following code but it only returns some html not the desired response
async function vendor_info() {
const options = {
uri: 'http://**.**.**.**/vendor/:username/pj1527',
json: true,
method: 'GET'
};
let vendor_info = undefined;
await requestPromise(options)
.then((body) => {
// err_token = 0;
vendor_info = body[0];
console.log(body);
// console.log(body[0]);
})
.catch(err => {
vendor_info = undefined;
// err_token = 1;
// console.log(err);
});
return vendor_info;
}
EDIT
It's working now, actually the url should be 'http://.../vendor//pj1527' in the request.
If you are using async await then there is no need to use then and catch blocks, Try like this:
async function vendor_info() {
try {
const options = {
uri: 'http://**.**.**.**/vendor/:username/pj1527',
json: true,
method: 'GET'
};
const vendor_info = await requestPromise(options);
console.log('vendor_info: => ', vendor_info);
return vendor_info;
} catch (err) {
console.log('Error: => ', err);
return err;
}
}
Hope this helps :)