Unable to solve this Express.js/ JavaScript programming issue [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
try {
console.log('11111')
const {
data: { tasks },
} = await axios.get('/api/v1/tasks')
console.log('22222 ' + await axios.get('/api/v1/tasks') )
console.log('33333 ' + tasks)
Issue is: tasks is undefined

The problem was in Backend..
the route associated with await axios.get('/api/v1/tasks') i.e get('/api/v1/tasks') had this code
``` const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json(tasks)
}
catch(error){
res.status(500).send({msg: error})
}
}```
instead above. It should be
```const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json({ tasks })
}
catch(error){
res.status(500).send({msg: error})
}
}```
The change is in res.status(200).json({ tasks })

Related

Why is next() is unreachable function end of try catch [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 days ago.
Improve this question
List item
enter image description here
I created the uploadProduct route in product.routes.js and I called it in the index.js file.
product.routes.js:
const express= require("express");
const uploadProduct = require("../controllers/product.controller");
const ProductValidation = require("../middlewares/validation/product.validation");
const router = express.Router()
router.post("/uploadProduct",ProductValidation.addProduct,uploadProduct)
module.exports = router
index.js:
const router = require("express").Router()
const product = require("./product.routes")
router.use(product)
module.exports = router
and this is where the problems occur
product.validation.js:
const joi = require("joi");
const APIError = require("../../utils/errors");
const Response = require("../../utils/response");
class ProductValidation {
constructor() {}
static addProduct = async (req, res, next) => {
const schema = await joi.object({
ProductName: joi.string().required().max(45).min(1),
NumberOfProducts: joi.number().required().max(45).min(1),
UnitOfMeasurment: joi.string().required().max(45).min(1),
PurchasePrice: joi.number().required(),
SellingPrice: joi.number().required(),
QRcode: joi.string().required().max(45).min(1),
// İmage: joi.string().required().max(45).min(1),
});
try {
const value = await schema.validateAsync(req.body);
return new Response(value, "success").created(res);
} catch (error) {
if (error.details && error?.details[0].message)
throw new APIError(error.details[0].message, 400);
else throw new APIError("Please comply with validation rules", 400);
}
next();
};
}
module.exports = ProductValidation;
it is middleware for the uploadProduct route. And why can't use the next () function at the end of trycatch.
I can use the next() function before trying catch returns but I can't use this function end of try-catch. Why? Can trying to catch block returns affect the next codes? Because any code after try-catch in this file is unexpected code!
Thanks :)

React JS Unexpected reserved word 'await' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am struggling with this async await issue I have created async function and for that I am calling await but I am getting error Unexpected reserved word 'await'
Below is the async function
export const addProductCall = async (product) => {
let accessToken = window.localStorage.getItem("accessToken");
await axios.post(SERVER_URI + '/inventoryservice/v1/item',
product,
{ headers: { "Authorization": "Bearer " + accessToken, "Content-Type": "application/json" } })
}
Below is the function from where I am calling this function.
const handleSubmit = () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}
You cannot use the await keyword outside of an async function :
const handleSubmit = () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}
should be :
const handleSubmit = async () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}
Replace
const handleSubmit = () => {
with
const handleSubmit = async () => {
For await to work, it needs to be wrapped inside an async function

URl works in postman returns full news array but returns empty in javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
In postman when i use the url below the news property on the response in full with articles
https://api.currentsapi.services/v1/search?country=us&language=en&apiKey="..."
But in javascript I'm getting an empty news array.
Here is the javascript:
function displayNewsResults(responseJson){
console.log(responseJson)
}
let newsBaseUrl = 'https://api.currentsapi.services/v1/search'
let newsApiKey = '...';
function getNews(country) {
let params = {
country: country,
language: 'us',
apiKey: newsApiKey
}
let queryString = formatQueryParams(params);
let url = newsBaseUrl + '?' + queryString;
console.log(url)
let req = new Request(url);
fetch(req)
.then(response => {
if (response.ok) {
return response.json();
}
else {
throw new Error(response.statusText);
}
})
.then(responseJson => displayNewsResults(responseJson))
.catch(err => {
$('#js-error-message-news').empty().text(`Something went wrong: ${err.message}`).show();
})
}
The function displayNewsResults returns:
{status: "ok", news: Array(0), page: 1}
The code seems correct and the result is also correct, the mistake however is that in your code you're calling the API with the language parameter set to us instead of en

Best way to list users with customClaims [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I just trying to list users in Firebase function
And I want to list just users if an admin (customClaims)
Now I do like this and its work
exports.listAdmins = functions.https.onRequest(async (req, res) => {
cors(req, res, () => {});
const token = req.body.token;
try {
const decodedToken = await admin.auth().verifyIdToken(token);
if (decodedToken) {
let users = [];
const list = async (nextPageToken) => {
await admin.auth().listUsers(1000, nextPageToken).then(async (result) => {
result.users.forEach((userRecord) => {
const user = userRecord.toJSON();
if (user.customClaims && user.customClaims.admin) {
users.push(user);
}
});
if (result.pageToken) {
await list(result.pageToken)
}
})
};
await list()
res.status(200).send({
success: 'SUCCESS',
users: users
});
}
} catch (error) {
res.status(500).send({error: 'SOMETHING_WRONG'});
}
});
But I was wondering about performance if I had many 100000 users?
Any better way to filter the list? by using admin.auth().listUsers() ?
As you can see from the API documentation for Auth.listUsers(), there is just listUsers(), and there is no alternative to filter users by any criteria. Listing many users could obviously be kind of an expensive operation. Consider instead storing information about your users in a database, and query the database instead.
You are also free to file a feature request for functionality that you think is missing from any Firebase SDK.

How the observable will return multiple values over time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
class Users {
constructor(private http: HTTPClient) {
}
const getUsers = this.http.get('url').map(res => res);
getUsers.subscribe( res => console.log('Response : ' +res) );
}
Here how getUsers observable will return multiple values over time.
Can someone please help me to understand on this. Thanks
You are doing an HTTP request there and since you are subscribed to getUsers, you will receive the response once it has been resolved.
It won't fire multiple times in your example.
But the power of being and Observable instead of a mere Promise here, is that you can you have the power of RxJS at your fingertips to do advanced data manipulations.
As an (maybe silly) example:
class Users {
constructor(private http: HTTPClient) {
}
const getUsers = this.http.get('url');
const users = getUsers.map(res => res.value.users);
users.map(users => users.map(user => user.name)).subscribe(userNames => { ... });
getUsers.subscribe( res => console.log('Response : ' +res) );
}

Categories

Resources