I used expo-image-picker to get the URI for the image that I am uploading to the MySQL database using Node.js. I can upload the image URI to the Database. The problem that I am facing is how do I call the image from the database and view it in my Front-End. the URI that I am getting is something like this
file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FdTracker-deb1436b-b1f4-483d-9499-47de5460a3b5/ImagePicker/a156533a-0666-406c-915d-7280e0910d20.jp
Now first of all I don't even know if the Image is stored in this URI. I tried opening it in the Browser, but nothing happened. I searched for the path defined in the URI on my device but couldn't find anything.
Second is how do I get the uploaded Image in my Front-end.
I wrote the following query to call the image back.
Image.getAllImageById = (id, result) => {
dbConn.query('SELECT * FROM receipt WHERE receiptId=?', id, (err, res) => {
if (err) {
console.log('Error while fetching receipt by Id', err);
result(null, err);
}
else {
console.log('Receipt fetched successfully');
result(null, res);
}
})
}
FYI- I am using React Native as Front-End, Node.js as Back-end and MySQL as Database.
Hoping to get a solution for my Problem.
Related
I am working on a simple API for searching using NodeJs and express, I coded in my server.js like this
app.get('/enduser/search/:keyword', function (req, res) {
let keyword = req.body.keyword;
if (!keyword) {
return res.status(400).send({ error: true, message: 'Please provide a keyword' });
}
dbConn.query("SELECT * FROM user_tbl WHERE cp_1 LIKE =? ", ['%' + keyword + '%'], (err, results) => {
if (err) throw err;
//return res.send({ err: false, data: results, message: 'Enduser search list.' });
return res.status(200).json({"status": 200, "err" : null, "data": results});
});
});
I got no errors when running on terminal, but i cannot get response when testing the API using postman. When I try to test using postman ... i got the error like this:
I tried some methods but still cannot figure out whats wrong.
First of all, its a bad practice to throw the error. You should always respond to user when developing a backend. Last thing you want is a timeout. I would say respond with error code 500.
Secondly, it seems like the problem in your db. That column doesn't exist. double check and confirm its actually there. Error 1054 refers to unknown column exception.
Also you can refer to this stackoverflow for a question with similar error code but on database side
https://dba.stackexchange.com/questions/162900/mysql-update-query-error-code-1054-unknown-column-in-field-list
I'm writing a method that uses async/await and promises to write some JSON to a file and then render a pug template. But for some reason the code that writes the JSON conflicts with the res.render() method resulting in the browser not being able to connect to the server.
The weird thing is that I don't get any errors in the console, and the JSON file is generated as expected — the page just won't render.
I'm using the fs-extra module to write to disk.
const fse = require('fs-extra');
exports.testJSON = async (req, res) => {
await fse.writeJson('./data/foo.json', {Key: '123'})
.then(function(){
console.log('JSON updated.')
})
.catch(function(err){
console.error(err);
});
res.render('frontpage', {
title: 'JSON Updated...',
});
}
I'm starting to think that there is something fundamental I'm not getting that conflicts with promises, writing to disk and/or express' res.render method. It's worth noting that res.send() works fine.
I've also tried a different NPM module to write the file (write-json-file). It gave me the exact same issue.
UPDATE:
So I'm an idiot. The problem has nothing to do with Express og the JSON file. It has to do with the fact that I'm running nodemon to automatically restart the server when files are changed. So as soon as the JSON file was saved the server would restart, stopping the process of rendering the page. Apologies to the awesome people trying to help me anyway. You still helped me get to the problem, so I really appreciate it!
Here's the actual problem:
The OP is running nodemon to restart the server whenever it see filechanges, and this is what stops the code from running, because as soon as the json file is generated the server restarts.
Efforts to troubleshoot:
It's going to take some trouble shooting to figure this out and since I need to show you code, I will put it in an answer even though I don't yet know what is causing the problem. I'd suggest you fully instrument things with this code:
const fse = require('fs-extra');
exports.testJSON = async (req, res) => {
try {
console.log(`1:cwd - ${process.cwd()}`);
await fse.writeJson('./data/foo.json', {Key: '123'})
.then(function(){
console.log('JSON updated.')
}).catch(function(err){
console.error(err);
});
console.log(`2:cwd - ${process.cwd()}`);
console.log("about to call res.render()");
res.render('frontpage', {title: 'JSON Updated...',}, (err, html) => {
if (err) {
console.log(`res.render() error: ${err}`);
res.status(500).send("render error");
} else {
console.log("res.render() success 1");
console.log(`render length: ${html.length}`);
console.log(`render string (first part): ${html.slice(0, 20}`);
res.send(html);
console.log("res.render() success 2");
}
});
console.log("after calling res.render()");
} catch(e) {
console.log(`exception caught: ${e}`);
res.status(500).send("unknown exception");
}
}
I have two problems, I need to be able to redirect users from facebook permissions acceptance from passportjs-facebook and from paypal payments redirect but I don't know how to do this in angular. I need to access posted JSON data coming from my own express server with an angular route which receives and uses that data.
If I do an a href="/auth" login button it sends my user to facebook's page to grant app permissions, after they do it redirects them to /auth/facebook/callback which is a blank white page with this json: {"ok":true,"status":"Login successful","success":true,"token":"...", user: {..}, }. How do I make it so they are redirected back to a page on my angular2 app and that this token is read into a json object within my apps so I can put it in local storage? This is my backend code:
userRouter.get('/auth', passport.authenticate('facebook', {scope: ['public_profile', 'user_friends', 'email']}), (req, res) => {});
userRouter.get('/auth/facebook/callback', function(req,res,next){
passport.authenticate('facebook', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Login failed'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful',
success: true,
token: token
});
});
})(req,res,next);
});
I'd use a res.redirect to the URL of one of your Angular pages, and include the token as a query string.
res.redirect('/#!/myprofile?token=MYTOKEN'); instead of the res.status(200).json... code
Alternatively you can parse the query string sent with the redirect right away in Angular as in this example, but I think that way can be a bit messy. That example will also help you through accessing query strings in Angular2.
I am looking to perform multiple actions upon receiving HTML(or EJS) form content using the POST method. I am using Node express, mongoose & mongoDB. Each of the below POST responses work individually but i am unsure how to proceed in updating multiple databases based on ONE SINGLE form submission.
// insert into passport db
app.post('/signup', passport.authenticate('local-signup',
{
successRedirect : '/index', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
//insert into my database here
[the content of in the second function is unimportant as that is working fine and has been stripped down for simplification.]
app.post('/signup', function( req, res )
{
new UserDB(
{
user_id : req.body.content,
first_name : req.body.fname,
}).save( function( err, mySite, count )
{
res.redirect( '/index' );
});
});
I have tried redirecting but the form content is not accessible after the redirect so only the first function stores the data (ie. only 1 database is filled).
How would i run both functions within
app.post('/signup',.....
{
...
});
?
Thanks in advance!
You can do this by making one function the callback of the other. This is easy because each function maintains the same Connect middleware signature, function(req, res, next), where req and res are the request and response objects created and manipulated by the application, and next is the next function to call at the end of the current function's execution.
According to the official documentation, passport.authenticate() is a normal piece of middleware. All you need to do is specify the middleware you want to be called next. Express queues middleware functions in the order in which you pass them into app.post. You can do something like this:
app.post('/signup', passport.authenticate('local-signup', {
failureRedirect : '/signup',
failureFlash : true
}),
function(req, res) {
new UserDB({
user_id : req.body.content,
first_name : req.body.fname,
}).save(function(err, mySite, count) {
res.redirect('/index');
});
});
Middleware is an extremely powerful feature of the Express framework and possibly the single most important one to master. This guide would be a great next step if you want to learn more.
I use node.js and mysql module to write a simple select statement.
The problem is it can only respond to one request, subsequent responses will be empty.
I use a browser to load the page for the first time, it return a complete result, but the browser is still loading. What happen:
Code:
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
client.query('SELECT * FROM ' + tbl,
function selectDb(err, results, fields) {
if (err) {
throw err;
}
for (var i in results){
var result = results[i];
response.write(result['CUSTOMERNAME']); // Writes to the web browser the value of test then a : to seperate values
}
response.end("END RESULT");
client.end();
}
);
});
According to the node-mysql docs (which I assume you are using) found here,
client.end();
Closes the mysql connection.
When you attempt another request, there is no open connection and node-mysql doesn't do any connection pool handling or auto re-connect, its all left up to you.
If you don't mind keeping a single connection open for the lifetime of the app (not the best design) you can just move that client.end() outside your connection handler.
Otherwise, create a little method that checks for an open connection or maybe does a connection pool, see this post for more info.