I have a problem with my code, when the page is loading and the code is starting running The code works very fast, and even before it is enough to reach all the lines it already continues to run.
What happens is that the page does not get the data disability and I'm not getting the users right way.
Here is my code:
var users = [{}]
getUsers();
function getUsers() {
const res = http.get('users/')
.then(res => {
users = res.data
})
.catch(function (error) {
console.log(error);
})
}
mock.onPost('/api/auth/access-token').reply(config => {
const data = JSON.parse(config.data);
const { access_token } = data;
try {
const { id } = jwt.verify(access_token, jwtConfig.secret);
const usersID = window.localStorage.getItem('usersId')
const user = _.cloneDeep(users.find(_user => _user.uuid === usersID));
delete user.password;
const updatedAccessToken = jwt.sign({ id: user.uuid }, jwtConfig.secret, { expiresIn: jwtConfig.expiresIn });
const response = {
user,
access_token: updatedAccessToken
};
return [200, response];
} catch (e) {
const error = 'Invalid access token detected';
return [401, { error }];
}
});
if you have an idea how to fix the code I will be very happy.
Thanks
Related
Hi i'm using MeaningCloud's api to get the proper object back once it analyses a string of text or a url for the Natural language processing (NLP). But it doesn't return the proper object.
Right now the code returns a string with the text "[Object object]" on the HTML page. I need it to return the results of the api call which returns the proper JSON object(that I can see in the console) in a proper "key/value" pair format on the HTML page.
Here's my script:
const baseURL = "https://api.meaningcloud.com/sentiment-2.1";
const key = "Your_api_key";
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const url = document.getElementById("url").value;
if (url !== "") {
getData(baseURL, url, key)
.then(function (data) {
postData("/add", { data: data });
}).then(function () {
receiveData()
}).catch(function (error) {
console.log(error);
alert("Invalid input");
})
}
})
const getData = async (baseURL, url, key) => {
const res = await fetch(`${baseURL}?key=${key}&txt=${url}`)
try {
const data = await res.json();
return data;
}
catch (error) {
console.log("error", error);
}
}
const postData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data
})
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log(error);
}
};
const receiveData = async () => {
const request = await fetch('/all');
try {
// Transform into JSON
const allData = await request.json()
console.log(allData)
// Write updated data to DOM elements
document.getElementById('result').innerHTML = allData;
}
catch (error) {
console.log("error", error);
// appropriately handle the error
}
}
I have another main file that's the server.js file which I run using node server.js that renders the html page properly but the script doesn't render the results on the page properly. You can signup on meaningcloud for a free api key that has a very convenient number of calls you can make.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
I am trying to make a chat application project with abusive text detection. I found code for the chat application online and want to add text detection using Perspective API. The API has several attributes for toxicity, threat etc. I am able to set the attributes inside the API function but I am unable to access them outside it.
Here is the relevant code:-
const sendMessage = asyncHandler(async (req, res) => {
const { content, chatId } = req.body;
let toxicity, insult, profanity, threat;
if (!content || !chatId) {
console.log("Invalid data passed into request");
return res.sendStatus(400);
}
let newMessage = {
sender: req.user._id,
content: content,
chat: chatId,
toxicity: toxicity,
insult: insult,
profanity: profanity,
threat: threat,
};
let inputText = newMessage.content;
// Perspective API
google
.discoverAPI(process.env.DISCOVERY_URL)
.then((client) => {
const analyzeRequest = {
comment: {
text: inputText,
},
requestedAttributes: {
TOXICITY: {},
INSULT: {},
PROFANITY: {},
THREAT: {},
},
};
client.comments.analyze(
{
key: process.env.API_KEY,
resource: analyzeRequest,
},
(err, response) => {
if (err) throw err;
// console.log(JSON.stringify(response.data, null, 2));
toxicity = (response.data.attributeScores.TOXICITY.summaryScore.value * 100).toFixed(2);
insult = (response.data.attributeScores.INSULT.summaryScore.value * 100).toFixed(2);
profanity = (response.data.attributeScores.PROFANITY.summaryScore.value * 100).toFixed(2);
threat = (response.data.attributeScores.THREAT.summaryScore.value * 100).toFixed(2);
newMessage.toxicity = toxicity;
newMessage.insult = insult;
newMessage.profanity = profanity;
newMessage.threat = threat;
console.log("1-" + newMessage.toxicity); // This returns the desired output
}
);
})
.catch((err) => {
throw err;
});
//
console.log("2-" + newMessage.toxicity); // This returns undefined
try {
let message = await Message.create(newMessage);
message = await message.populate("sender", "name profilePic");
message = await message.populate("chat");
message = await User.populate(message, {
path: "chat.users",
select: "name profilePic email",
});
await Chat.findByIdAndUpdate(req.body.chatId, {
latestMessage: message,
});
res.json(message);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
});
I want newMessage to be updated after the API call. After coming across this post, I found that console.log("2-" + newMessage.toxicity) executes before console.log("1-" + newMessage.toxicity). I tried using callbacks and async/await but couldn't make it work.
The console.log("2-" + newMessage.toxicity) is outside the google.discoverAPI call so it execute instantly.
you can try something like this
const sendMessage = asyncHandler(async (req, res) => {
const { content, chatId } = req.body;
let toxicity, insult, profanity, threat;
if (!content || !chatId) {
console.log("Invalid data passed into request");
return res.sendStatus(400);
}
let newMessage = {
sender: req.user._id,
content: content,
chat: chatId,
toxicity: toxicity,
insult: insult,
profanity: profanity,
threat: threat,
};
let inputText = newMessage.content;
// Perspective API
const client = await google
.discoverAPI(process.env.DISCOVERY_URL)
const analyzeRequest = {
comment: {
text: inputText,
},
requestedAttributes: {
TOXICITY: {},
INSULT: {},
PROFANITY: {},
THREAT: {},
},
};
await new Promise((resolve, reject) => {
client.comments.analyze(
{
key: process.env.API_KEY,
resource: analyzeRequest,
},
(err, response) => {
if (err) {
reject(err)
}
// console.log(JSON.stringify(response.data, null, 2));
toxicity = (response.data.attributeScores.TOXICITY.summaryScore.value * 100).toFixed(2);
insult = (response.data.attributeScores.INSULT.summaryScore.value * 100).toFixed(2);
profanity = (response.data.attributeScores.PROFANITY.summaryScore.value * 100).toFixed(2);
threat = (response.data.attributeScores.THREAT.summaryScore.value * 100).toFixed(2);
newMessage.toxicity = toxicity;
newMessage.insult = insult;
newMessage.profanity = profanity;
newMessage.threat = threat;
console.log("1-" + newMessage.toxicity);
resolve()
}
);
})
.catch((err) => {
throw err;
});
//
console.log("2-" + newMessage.toxicity); // This returns undefined
try {
let message = await Message.create(newMessage);
message = await message.populate("sender", "name profilePic");
message = await message.populate("chat");
message = await User.populate(message, {
path: "chat.users",
select: "name profilePic email",
});
await Chat.findByIdAndUpdate(req.body.chatId, {
latestMessage: message,
});
res.json(message);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
});
I'm writing a telegram bot. There is a piece of working code that responds to messages from the user, searches for key word matching database and sends the result to user. The problem is that the sample result gets into the console, how to send it to the user? Please, help
bot.on('message', (ctx) => {
const text = ctx.text
const log = sequelize.query("SELECT book FROM books t WHERE (t.*)::text LIKE '%"+ text +"%'") .then( (result) => {
console.log(result,log)
}) .catch( (err) => {
console.log(err);
for (const result of results) {
ctx.reply(result.book);
}
})
})
Based on sendMessage api and data in message Your code should look like this:
const { QueryTypes } = sequelize;
bot.on('message', async (message) => {
const {text, chat} = message; // https://core.telegram.org/bots/api#message
const {id: chatId} = chat; // https://core.telegram.org/bots/api#chat
let response = '';
try {
const rows = await sequelize.query(
'SELECT book FROM books t WHERE (t.*)::text LIKE :searchText',
{
replacements: { searchText: `%${text}%` },
type: QueryTypes.SELECT,
}
);
console.log('ROWS:', rows);
if (rows.length) {
response = rows.map(row => row.book).join("\n");
}
else {
response = 'Book not found';
}
}
catch (error) {
console.error(error.message);
response = 'Unable to lookup';
}
finally {
if (response) {
bot.sendMessage(chatId, response);
}
}
})
Check manuals:
sendMessage
Message object
Chat object
Sequelize replacements
Here I am making a fetch request to an api -
export async function getServerSideProps(ctx) {
let id = ctx.params.id;
let userObject;
let userId;
const cookie = parseCookies(ctx);
if (cookie.auth) {
userObject = JSON.parse(cookie.auth);
userId = userObject.id;
}
if (!userId) {
return {
redirect: {
permanent: false,
destination: '/',
},
};
}
const res = await fetch(`http://localhost:3000/api/tests/${id}`);
console.log(await res.json());
const data = await res.json();
console.log(data);
// return {
// props: { product: data },
// };
return {
props: {},
};
}
Here I am reading data from firebase realtime database -
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
})
.then(() => res.status(200).json(obj))
.catch(err => console.log(err));
};
Which gives me this error -
Server Error FetchError: invalid json response body at https://localhost:3000/api/tests/-MUT5-DbK6Ff6CstPSGc reason: Unexpected end of JSON input
Everything seems to work except the json response I am getting after making fetch request. I can't even console.log to see what response I am actually getting. What am I missing?
Edit - Here's my firebase database structure, where test node is root node
There is no return in your promise. That's why obj is null. Instead of then just send the response in first capture.
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
res.status(200).json(obj)
})
.catch(err => console.log(err));
};
I´m using this code to retrieve my contacts list inside a firebase function following the
(https://github.com/googleapis/google-api-nodejs-client/blob/master/samples/people/contacts.js) example
const { google } = require('googleapis');
const clientAuth = require('./clientAuth');
exports.getGoogleContacts = functions.https.onCall(async (data, context) => {
console.log('getGoogleContacts- init function')
const contacts = google.people({
version: 'v1',
auth: clientAuth.oAuth2Client,
});
return new Promise((resolve, reject) => {
clientAuth
.authenticate(['https://www.googleapis.com/auth/contacts'])
.then(async () => {
console.log('after client auth')
contacts.people.connections.list({
resourceName: "people/me",
pageSize:200,
personFields: ['addresses',
'ageRanges',
'biographies',
'birthdays',
'braggingRights',
'coverPhotos'], // ... and many other fields
}, function (err, response) {
if (err) {
console.log('contacts.people.connections error')
console.log(err)
reject(new Error(err))
} else if (response) {
console.log('contacts.people.connections response')
console.log(response)
if (response.pageToken) {
// how could I continue to retrieve next page of contacts?
}
resolve(response)
}
})
})
})
})
If there is a nextPageToken, there is no working example I´ve was able to found.
edited - this code was able to solve the pagination with array concatenation
I was able to come up with this solution, even though now I´m facing a problem of pushing to the connections array... It´s not working
const listOptions = {
resourceName: "people/me",
pageSize: 200,
personFields: ['addre...']
}
async function getConnectionsList(contacts, nextPageToken) {
if (!nextPageToken) {
return contacts.people.connections.list(listOptions)
} else {
listOptions.pageToken = nextPageToken
return contacts.people.connections.list(listOptions)
}
}
let response = await getConnectionsList(contacts)
let nextPage = response.data.nextPageToken
let connections = response.data.connections
while (nextPage) {
nextPage = await getConnectionsList(contacts, nextPage)
connections.push(nextPage.data.connections) // not working
connections.concat(nextPage.data.connections) // also not working...
nextPage = nextPage.data.nextPageToken
console.log('hasNextPage?', nextPage)
}
console.log('connections',connections)
resolve(connections)