Sending "data" in res.send(), gives error on front end - javascript

I want to send the data in res.send(data). When i
console.log("This dox data",text);
in terminal, it works fine. It logs all text content in terminal. But accessing at frontend it gives me error
router.get("/api/emailtemplates/data/:subject", (req, res) => {
Email_templates.find({subject: req.params.subject}, (err, data) => {
if (!err) {
const val = data[0]['template_file_link'];
console.log(val);
const data= textract.fromFileWithPath(val, function( error, text ) {
console.log("This dox data",text);
});
res.send(data);
} else {
console.log(err);
}
});

You were trying to return wrong thing you need to send response in callback of the textract function
router.get('/api/emailtemplates/data/:subject', async (req, res) => {
try {
const templates = await Email_templates.find({ subject: req.params.subject });
const val = templates[0].template_file_link;
console.log(val);
textract.fromFileWithPath(val, (error, text) => {
console.log('This dox data', text);
return res.json({ text });
});
} catch (error) {
console.log(error);
return res.status(500).json({ error: true });
}
});

That code will give you the error Uncaught ReferenceError: Cannot access 'data' before initialization. You're trying to use the data constant you've declared within the if (!err) block before that constant has been initialized, because you've used data both as the name of the parameter you're going to receive the data from Email_templates.find in and also as the constant you store the result of textract.fromFileWithPath in. Here's a simpler example of the problem:
function example(err, data) {
// ^^^^−−−−−−− parameter called `data`
if (!err) {
const val = data[0]['template_file_link'];
// ^^^^−−−−−−−−− ReferenceError here
// because this is trying to use
// the constant below before it's
// initialized (it's in the "Temporal
// Dead Zone")
const data = "whatever";
}
}
example(null, [{template_file_link: ""}]);
Use different names for them. For instance:
router.get("/api/emailtemplates/data/:subject", (req, res) => {
Email_templates.find({subject: req.params.subject}, (err, data) => {
if (!err) {
const val = data[0]['template_file_link'];
console.log(val);
const fileData = textract.fromFileWithPath(val, function( error, text ) {
// ^^^^^^^^
console.log("This dox data",text);
});
res.send(fileData);
// ^^^^^^^^
} else {
console.log(err);
}
});
});

Related

Redis get function

I'm getting github repo data, and then i store it in redis with set. with get am getting current data, but when i trying add function to get it's not working.
let redisClient;
(async () => {
redisClient = redis.createClient();
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.on("connect", function () {
console.log("Redis Connected!");
});
await redisClient.connect();
})();
// Make request to Github for data
async function getRepos(req, res, next) {
try {
console.log("Fetching Data...");
const { username } = req.params;
// with this am getting result
const cacheResults = await redisClient.get(username);
console.log(cacheResults);
// with this am not getting result, how can i fix this?
redisClient.get(username, (err, data) => {
console.log(data);
});
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// Set data to Redis
redisClient.set(username, JSON.stringify(repos));
res.send(setResponse(username, repos));
} catch (e) {
console.log(e);
res.status(500);
}
}
it's don't console.log(data), i searched a lot and everyone have one example how to use get function, but in me case it's don't log, whats am doing wrong?
this is my cache function
// Cache middleware
async function cache(req, res, next) {
const { username } = req.params;
try {
await redisClient.get(username).then((data) => {
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
});
} catch (error) {
console.log(error.toString());
}
}
app.get("/repos/:username", cache, getRepos);
it's works, but time finish times with cache and without it are same? am doing something wrong?
can you try like this
redisClient.get(username).then((data) => {
console.log(data);
});

Unable to access user info object property - facebook chat api

I'm using Facebook chat api to create a simple cli script that will reply to messages that are sent to my facebook account. I'm trying to assign and get the user name and my name to use them inside the reply but they are always undefined. I think that the object property aren't assigned correctly. Is there a fix for this?
require('dotenv').config();
const fs = require('fs');
const fb = require('facebook-chat-api');
const path = require('path');
const appStateFile = path.format({ dir: __dirname, base: 'appstate.json' });
let currentUser = null;
if( !fs.existsSync(appStateFile) ){
//debug .env
console.log(process.env);
fb({email: process.env.FB_EMAIL, password: process.env.FB_PWD}, (err, api) => {
if(err){
return console.log(err);
}
console.log(api);
api.setOptions({
listenEvents: true
});
fs.writeFileSync(appStateFile, JSON.stringify(api.getAppState()));
let id = api.getCurrentUserID();
api.getUserInfo(id, (err, profile) => {
console.log(profile); // profile is logged correctly
currentUser = profile;
});
api.listenMqtt( (err, event) => {
if(err){
return console.log(err);
}
if(event.type === 'message'){
console.log(event.body)
api.getUserInfo(event.senderID, (err, user) => {
if(err){
return console.log(err);
}
console.log(user); // user object is logged correctly
api.sendMessage('...', event.threadID)
});
}
});
});
}else{
fb({appState: JSON.parse(fs.readFileSync(appStateFile))}, (err, api) => {
if(err){
return console.log(err);
}
console.log(api);
api.setOptions({
listenEvents: true
});
let id = api.getCurrentUserID();
api.getUserInfo(id, (err, profile) => {
console.log(profile);
currentUser = profile;
});
api.listenMqtt( (err, event) => {
if(err){
return console.log(err);
}
if(event.type === 'message'){
console.log(event.body)
api.getUserInfo(event.senderID, (err, user) => {
if(err){
return console.log(err);
}
console.log(user)
api.sendMessage(`FB Pager v1.0.\nHi ${user.name}!Your message was forwarded with an email to ${currentUser.name}.`, event.threadID)
});
}
});
});
}
I think the problem here is that api.getUserInfo is asynchronous.
So you would need to nest them to get it to work.
Or you can try this, since getUSerInfo allows you to add an array of user ids to get the data for:
api.listenMqtt((err, event) => {
if (err) {
return console.log(err);
}
if (event.type === "message") {
const currentUserId = api.getCurrentUserID();
const senderId = event.senderID;
api.getUserInfo([currentUserId, senderId], (err, ret) => {
if(err) return console.error(err);
// Ret should contain the two users
// See: https://github.com/Schmavery/facebook-chat-api/blob/master/DOCS.md#getUserInfo
console.log(ret);
});
}
});
Nesting user calls method:
api.listenMqtt((err, event) => {
if (err) {
return console.log(err);
}
if (event.type === "message") {
let currentUserId = api.getCurrentUserID();
api.getUserInfo(currentUserId, (err1, signedInUser) => {
if (err1) {
return console.log(err);
}
api.getUserInfo(event.senderID, (err2, userInMessage) => {
if (err2) {
return console.log(err);
}
console.log(signedInUser, userInMessage)
api.sendMessage("...", event.threadID);
});
});
}
});
After a lot of debug I've found the correct way to access the needed informations. Since the user informations after that are retrived are mapped to another object that is the userId, the only way to access to each property is to use a for loop. Initially I was thinking that this can be avoided but unfortunately it's necessary otherwise using only dot notation will result in undefined. This is how I've solved
api.getUserInfo(userId, (err, user) => {
let username;
if(err){
return console.log(err);
}
for(var prop in user){
username = user[prop].name;
}
api.sendMessage(`Hello ${username!}`, event.threadID);
});

Cannot set headers after they are sent to client Expressjs router

I'm getting error cannot set headers on express js, I think the problem is have to write setHeader, i was set but stil can't, this my code:
router.get('/cek', (req, res) => {
const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);
child.stdout.on('data',
function (data) {
value = (JSON.stringify(data));
x = value.split('.');
y = JSON.stringify(x[2])
result = y.replace(/\D/g, "");
res.setHeader('Content-Type', 'text/html');
res.send(result);
}
);
child.stderr.on('data',
function (data) {
console.log('err data: ' + data);
}
);
});
I tired to fixing this error for two days, but still cannot, anybody can help?
As stated by Frederico Ibba, this is usually caused after res.send is sent and there is still data being processed... Your workaround for this may simply be to receive all the data before sending it out using res.send. You can try this.
async function executeCommand() {
return new Promise((resolve, reject) => {
const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);
child.stdout.on('data',
function (data) {
value = (JSON.stringify(data));
x = value.split('.');
y = JSON.stringify(x[2])
result = y.replace(/\D/g, "");
resolve(result);
}
);
child.stderr.on('data',
function (err) { // Renamed data for err for clarification
reject(err);
}
);
});
}
router.get('/url', async (req, res) => {
try {
const result = await executeCommand();
res.setHeader('Content-Type', 'text/html');
res.send(result);
} catch(error) {
// There was an error. I'm throwing a 500
res.sendStatus(500);
}
});
Note that this will be effective only if you are confident that the data is being fired once, as indicated by skirtle

Passing a variable from ReactJS frontend to NodeJS back end using a GET route

I am working on a react app and am trying to find a way to pass a variable I define in my front-end (Question.js) to my back-end (server.js) so that I can issue different queries. I have the code
//Question.js
state = {
data: null
};
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
//server.js
con.connect(function (err) {
if (err) throw err;
con.query("SELECT question FROM s1questions WHERE ID = 1", function (err, result, fields) {
if (err) throw err;
app.get('/express_backend', (req, res) => {
var x = JSON.stringify(result[0].question);
res.send({ express: `${x}` });
});
});
});
Your sever should probably split your database connection from your route handler definitions. Also, you could use query parameters to access questions based on their id in the database.
// question.js
callBackendAPI = async () => {
const response = await fetch(`/express_backend?questionId=1`);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
// server.js
app.get('/express_backend', (req, res) => {
const { questionId } = req.query;
// query database for question by id
});

What cause "Error: Uncaught (in promise): Response with status:200 for Url:null" to show up?

I'm accessing a Mongo database through NodeJS and Express as below:
var MongoClient = require('mongodb').MongoClient;
...
app.get("/app/visits", function (req, res, next) {
console.log("get visits");
MongoClient.connect('mongodb://localhost:27017/db', function (err, db) {
if (!err) { console.log("We are connected"); }
visits = db.collection('visits', function (err, collection) { });
visits.find().toArray(function (err, user) {
this.user = JSON.stringify(user);
if (err) { throw err; } else console.dir(this.user);
});
res.send(this.user);
});
});
In the browser this works fine. If I change res.send(this.user); to res.status(301).send(this.user); the status is also changed.
But the problem, Angular 2 with native script code returns the error:
getActualVisits()
{
return this.http.get("http://localhost:1234/app/visits").map(response => response.json())
}
I have no idea WHY after 7 hours of trying repair that.
Method getActualVisits() is calling from:
getActualSpecialization() {
let v = this.getActualVisits();
...
}
You need to call .subscribe after .map in order to observe the values that are returned.
getActualVisits() {
return this.http.get("http://localhost:1234/app/visits")
.map(response => response.json())
.subscribe(
data => this.actualVisits = data,
err => this.logError(err),
() => console.log('get actual visits complete')
);
}
See the following docs for more information https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

Categories

Resources