Using Express.js's res.send() with async.each - express

async1.each(arr, function(arrayMember) {
orders.where('name', arrayMember).fetch({withRelated: ['allOrders']}).
then(function(dd2, callback) {
dd2 = dd2.toJSON();
var sendMemberOrder = {};
sendMemberOrder.name = dd2.name;
sendMemberOrder.lastOrder = dd2.allOrders.length;
res.send(sendMemberOrder);
});
}, function(err) {
if (err) {
console.log("err");
}
});
I'm trying to use Express's res.send() feature but given that I'm using async.each, I'm getting
headers already sent
error.
How can I pass the result of each iteration as an array when a request is being made?

Since you already use promises here, I would like to doscourage you from using async.js here. Your code is broken anyway as it does not call callback at all, and the callback parameter is declared on the wrong function. Instead you could try this:
app.get(your_route, function(req, res, next) {
// obtain arr
Promise.all(arr.map(function(arrayMember) {
return orders.where('name', arrayMember)
.fetch({withRelated: ['allOrders']})
.then(function(dd2) {
dd2 = dd2.toJSON();
return {
name: dd2.name,
lastOrder: dd2.allOrders.length
};
});
})).then(function(resultData) {
res.send(resultData);
}).catch(function(err) {
console.log(err);
next(err);
});
});

Related

postman req not responding any data even not responding error

Login routes:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({
mobileNo: req.body.mobileNo,
});
if (!user) {
res.status(401).json("You are not registerd");
}
const password = res.body.password;
if (password === user.password) {
return res.status(200).json("You are logged in");
} else {
return res.status(501).json("Naah! wrong pass");
}
} catch {
(err) => {
res.status(500).json(err);
};
}
});
module.exports = router;
index.js:
app.use("/api/auth", authRoute);
import:
const authRoute = require("./routes/auth");
My postman image, I am not getting any result.
Your try-catch syntax is wrong, correct would be
try {
...
} catch(err) {
res.status(500).json(err);
}
With your syntax, when the catch block is reached, the res.status(500).json(err) statement is not executed, therefore the request never comes back.
In your try block, there are 3 responses available. If the first condition in the if block is also executed with another one of the responses in the below if-else condition this problem may occur. Because at a time, sending 2 responses is impossible. Therefore, you should return that response and terminate.
if (!user) {
return res.status(401).json("You are not registered");
}

Sequelize, findOrCreate + findAll unexpected behavior

I'm trying to fetch data from a dog API and I want to add to my database only their temperaments. I tried using some loops and a split to isolate the data and then using
findOrCreate() to add only those who are not already in the DB, after that I use findAll()
to get that info from the DB to send it using expressJS.
The unexpected behavior comes when I go to the route that executes all this and the route
only gives about half of the temperaments (they are 124 and it displays arround 54), then when I refresh the page it shows all 124 of them. The DB gets populated with all the 124 in one go so the problem is with findAll()
This is the function that isolates the temperaments and append them to the DB:
module.exports = async () => {
const info = await getAllDogs();
info.forEach(async (element) => {
const { temperament } = element;
if (temperament) {
const eachOne = temperament.split(", ");
for (i in eachOne) {
await Temperament.findOrCreate({
where: { name: eachOne[i] },
});
}
}
});
};
And this is the code that gets executed when I hit my expressJS sv to get the info
exports.temperaments = async (req, res) => {
try {
await getTemperaments(); //this function is the above function
} catch (error) {
res.status(500).send("something gone wrong", error);
}
const temperamentsDB = await Temperament.findAll();
res.json(temperamentsDB);
};
So as you can see the last function executes the function that appends all the data to the DB and then sends it with findAll and res.json()
forEach is a synchronous method so it doesn't await a result of the async callback. You need to do for of in order to get wait for all results:
module.exports = async () => {
const info = await getAllDogs();
for (element of info) {
const { temperament } = element;
if (temperament) {
const eachOne = temperament.split(", ");
for (i in eachOne) {
await Temperament.findOrCreate({
where: { name: eachOne[i] },
});
}
}
}
};

Why am I not getting a response from express server?

Sending a logout request to my server but I'm never getting a reply. The logout function is being called and the userID key is being deleted from my redis cache but I never get a response. Here's my code.
export const logout = async (req, res) => {
console.log("logout called");
const { userID } = req.user;
client.del(userID.toString, (err, reply) => {
console.log("inside client.del");
if (err) {
return res.status(500);
} else {
return res.status(200);
}
});
};
Because of callback, you should use promise
export const logout = async (req, res) => {
return new Promise((resolve,reject) => {
console.log("logout called");
const { userID } = req.user;
client.del(userID.toString, (err, reply) => {
console.log("inside client.del");
if (err) {
reject(res.status(500));
} else {
resolve(res.status(200));
}
});
});
}
res.status() does not send a response from the server. All it does is set the status as a property on the response object that will go with some future call that actually sends the response.
It is meant to be used in something like this:
res.status(500).send("Database error");
If you look at the Express doc for res.status(), you will see these examples:
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
And, see that they all are followed by some other method that actually causes the response to be sent.
And, if you still had any doubt, you can look in the Express code repository and see this:
res.status = function status(code) {
this.statusCode = code;
return this;
};
Which shows that it's just setting a property on the response object and not actually sending the response yet.
You can use res.sendStatus() instead which will BOTH set the status and send the response:
export const logout = (req, res) => {
console.log("logout called");
const { userID } = req.user;
client.del(userID.toString, (err, reply) => {
console.log("inside client.del");
if (err) {
res.sendStatus(500);
} else {
res.sendStatus(200);
}
});
};
Note, I removed the two return keywords since they don't accomplish anything useful in this particular context.
I also removed the async keyword from the function definition since it was not doing anything useful in this context.

Variable in data section can't get API response value (response.data)

I accessed API to upload image and return the image URL with Vue app. I want to set API response value to imgUrl1 in data section. I' sure getting correct response in console but imgUrl1 is still empty. Anybody idea ?? Thank you so much !
Vue
data () {return
{
imgUrl1:'',→empty
}
},
methods: {
uploadFile1: function () {
var img_file1 = this.$refs.img1.files[0]
var params = new FormData()
params.append('image', img_file1)
params.append('client_name', this.tableSelected)
axios.post("http://127.0.0.1:5000/", params
).then(function (response) {
console.log(response.data)→image url exists
this.imgUrl1 = response.data
}).catch(function (error) {
for(let key of Object.keys(error)) {
console.log(key);
console.log(error[key]);
}
});
}
console.log(response.data)
https://storage.googleapis.com/dashboard_chichat/img/クライアント名/xxxxxxxxnQSkX6Wudy.jpg
try using arrow functions in your then callback so the value of this is your Vue component.
methods: {
uploadFile() {
...
axios.post('', params)
.then((response) => {
this.imgUrl1 = response.data
})
}
}
the equivalent of it without arrow functions is:
methods: {
uploadFile() {
...
const _this = this;
axios.post('', params)
.then(function (response) {
_this.imgUrl1 = response.data
})
}
}

Display multiple Oracle SQL query results on AngularJS page

So I need to display multiple results of SQL query on the same component in AngularJS.
How would I do this? So far, I understood that component can treat only one http request as in here:
'use strict';
angular.module('cryostat', []).component('cryostat', {
templateUrl: 'cryostat/cryostat.template.html',
controller: function cryostatController($http) {
this.pageTitle = "NP04 Cryostat"
this.natalie = 1;
$http.get("cryostat.conn.php")
.then(function (response) {this.TT0101 = response.data.records;});
}
});
I understood that component can treat only one http request
This is not at all true. Where did you hear that? It is easy to make two requests simultaneously with $q.all():
var promiseOne = $http.get("query1.php");
var promiseTwo = $http.get("query2.php");
$q.all([promiseOne, promiseTwo]).then(function(resultArray) {
$scope.resultOne = resultArray[0];
$scope.resultTwo = resultArray[1];
});
Make use of $q.all() for your purpose.
var myData_One, myData_two;
var promises = [];
function promiseA() {
let deferred = $q.defer();
ajaxCall().then((response) => {
$scope.myData_One = response;
deferred.resolve();
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
function promiseB() {
let deferred = $q.defer();
ajaxCall().then((response) => {
$scope.myData_two = response;
deferred.resolve(response);
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
var promises = [promiseA(), promiseB()];
$q.all(promises).then((values) => {
//Do whatever you wish to with response data from both promises.
});