I am new developer ReactJS, I develop a table with ReactJS on the FrontEnd, NodeJS on BackEnd and MySQL about the database.
I want when I click on the view button on Action column, it will be redirected to another page, which display a list containing the result of the Select query, as below :
My router :
exports.viewclient = function(req, res) {
var Code = req.query.Code;
console.log(req.query.Code);
connection.query('SELECT Code, Prenom, Nom, FAX, Telephone, Email, Adresse1, Adresse2 FROM clients WHERE Code = ?',[Code], function(error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
console.log(results);
});
}
My server :
router.get('/viewclient/:Code', clients.viewclient);
When, I test the backend with Postman, http://localhost:4000/app/viewclient/:Code=1111 , it returns : [] and console.log(req.query.Code) returns undefined
How to fix that please ?
Need a couple of changes in your URL and code
The URL should be http://localhost:4000/app/viewclient/111
In your controller
console.log(req.params);
Output
{ "Code": "111"}
Related
I am trying to write a simple login page using node.js, HTML, and MySQL. A problem I ran into was adding entries to my sql db.
con.connect(function(err) {
if (err) throw err;
});
app.post('/create', function(req, res) {
var info ={
"usernamec":req.body.USERC,
"passwordc": req.body.PASSC
}
con.query('INSERT INTO users SET ?',info, function(err, result){
console.log(result);
});
});
Everything seems to be working except for the actual query, which returns undefined. What could I be doing wrong? The picture below is my database.
solution:
Change or Modify in Column name when you can assign the values (usernamec, passwordc) this one.
let info ={"username": req.body.USERC,"password": req.body.PASSC}
whenever you can insert the data Column name will be same as the Database table Col name.means Both are same not different
Firstly, please check your request params(USERC, PASSW)DataType and
Values.
then Second thing, console the error
con.query('INSERT INTO users SET ?',info, function(err, result){
if(err)
console.log(err);
console.log(result);
});
});
InCase Query Error you can get and resolved it.
Another Simple Way runs the Query in PHPMyadmin Manually.
Example:
INSERT INTO users SET `username`= 1 and `password` =`HELLO MYSQL`;
How can I retrieve data from database(MySQL) dynamically in NodeJS when having more than one events in the database table. In the below code, I am getting data in text variable...have checked it via console but want it to get retrieved from SQL query ....so what is the correct way to get the data dynamically via query
console.log("enter to db-----------------",text)
connection.query("SELECT Description FROM tegbot_v4_xlsx WHERE Name=text", async function (error, rows, fields)
{
if (!!error)
{
console.log(`Error in the query`)
}
else
{
console.log(`Successful query\n`);
console.log('hello---------', rows[0].Description)
await dc.context.sendActivity(rows.Description)
}
})
I have a problem I need help with a question. So the problem is I have a route to display all rows of my students table and it works, but know when I try the code below to search for a specific student_id I get:
"Failed to query for users: Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'where clause'"
I have tried the queryString as:
My table has student_id, firstName, lastName, checkIn, and checkOut as columns.
They are all VARCHARS.
queryString = SELECT * FROM students WHERE student_id = ${id}
queryString = SELECT * FROM students WHERE student_id = ? and then getConnection().query(queryString, [id], (err, rows, fields) => {
But I get the same error, I would really appreciate the help.
The question that I have would be implementing after all my different search routes work as intended to display the data nicely in html, but I'm new to this and I can't find anything to help me with this problem. I would like it to display as a list almost like MySQL displays it. Is that possible? I'm using the ejs view engine as my html pages.
// Route to search by id
router.get("/searchById", (req, res) => {
const id = req.body.id
queryString = `SELECT * FROM students WHERE student_id = ${id}`
getConnection().query(queryString, (err, rows, fields) => {
// If error occures
if(err) {
console.log("Failed to query for users: " + err)
res.sendStatus(500)
return
}
if(rows) {
console.log(rows)
console.log("We fetched Students successfully")
res.json(rows)
}
})
})
For GET request you should use req.query.id
For post request you should use req.body.id
In your code you have used get request and tried to fetch req.body.id
I am relatively new to Node and Meteor and am trying to retrieve the insert ID of a MySQL query using the numtal:mysql package. The trouble I run into is the query function running on the server and not returning to the client. I need the ID to return to the client so I can route the client to the newly created entry.
Client:
Template.new.events({
'click .button.submit' : function(){
Meteor.call('demoFunc', function(error, result){
console.log(result);
});
},
});
Server:
Meteor.methods({
demoFunc:function(){
//construct deal object
var newDeal = {
dealer_id : 1,
client_id : 1
};
//deal query
liveDb.db.query('INSERT INTO deal SET ?', newDeal, function(err, result){
return result.returnId;
});
}
});
If I could get the result.returnId in the demoFunc method to return to the client then I would be golden. If anyone's run into anything like this or worked around this, any help would be greatly appreciated.
The best place to ask that is at https://github.com/numtel/meteor-mysql/issues
This is a community packages and I highly recommend not to use it in production, only for learning/fun. You can also contribute to this repo by adding that feature that you want.
It is expect that Meteor will support MySQL soon. Meteor bought Fatomdb: http://techcrunch.com/2014/10/07/meteor-acquires-yc-alum-fathomdb-for-its-web-development-platform/
I've had the same issue and solved the problem with this package usefulio:sync-methods. You can see how the package works in Github.
This package automatically adds a callback function to every syncMethod defined in server side. So, you can just call this callback function from inside the server method, after the async results have been processed.
So, the steps are:
1) Install the package: meteor add usefulio:sync-methods
2) Declare your method as a syncMethod like this:
Meteor.syncMethods({
demoFunc:function(callback){
//construct deal object
var newDeal = { dealer_id : 1, client_id : 1 };
//deal query
liveDb.db.query('INSERT INTO deal SET ?', newDeal, function(err, result){
callback(undefined, result.returnId);
});
}
});
3) On the client side, you just call the method in the Meteor way:
Meteor.call('demoFunc', function(err, result){
...
});
I have started nodejs to make a simple chat application in it.
For this I want to access all users which are in mysql database.
My code is like:
JS
exports.authenticate = function(req, res) {
//connection.connect();
var sql="SELECT * from users where username='"+req.body.user+"' and password='"+req.body.pass+"' LIMIT 1";
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows);
var str="Hi, <b>"+rows[0].name+"</b> ("+rows[0].email+")";
sql="SELECT DISTINCT username,name from users ORDER BY name";
connection.query(sql, function(err, datarows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows+' <br/> All Users are : ', datarows.length+"<a href='/'>Login</a>");
str+='<ul style="list-style:none;width:300px">';
for(var index=0;index<datarows.length;index++)
{
str+="<li><a href='javascript:;'>"+datarows[index].name+", "+datarows[index].email+"</a></li>";
}
str+='</ul>';console.log(str);
console.log(str)//gives ul
});
str+="<a href='/'>Login</a>";
res.send(str);//this not gives the ul of other users
});
}
The above code has problems that I wrote console.log(str)//gives ul this prints the whole string like Hi, <b>Rohan</b> ("rohan#xyz.com")<ul><li><a>Something</a></li>....</ul>. But res.send(str); sends only Hi, <b>Rohan</b> ("rohan#xyz.com")<a href='/'>Login</a>.
Why this is happening?
Is my str variable not global?
Can I use res.send() many times, if yes then how?
Can I use the above code with jade then what code should I write for this.
I found this answer How to pass data form mongodb (using Mongous module) into nodejs view (using temp engine jade)? related to my problem
app.get('/', function(req, res) {
mgs(dbColl).find(function(data){
res.render('yourview.jade', { data: data });
});
});
Then,How to access data in yourview.jade
I also want to know for which type of applications we should use nodejs ?
Thank in advance.
This is happening because Node is asynchronous. Your res.send(str) is executed immediately after calling your inner connection.query(), therefore the callback which adds more hasn't executed before the send.
No, your str variable is not global.
I do not believe so. If you want to write to the response before sending it, you can use res.write().
Yes you can use Jade instead of what you're doing now. Take a look at the Jade docs. They are full of examples of variables being used in jade. To summarize it for you though, you should be able to access a variable with #{variable}.
As for your last question, I'm really not sure what you're asking. You can use node for alot of stuff, from controlling quadcopters to web sites and services.