i'm having a problem in posting/inserting a data in my redis database via POST method. By the way i'm using expressjs as framework and here is my code:
app.post('/create/:id', function (req, res) {
return client.set(req.params.id, req.params.val, function (err, data) {
if (!err) {
return res.send(data);
} else {
return console.log(err);
}
});
});
Is there any correction here? My goal is to post data like this http://mydomain:45/create/2/test is it possible? or do I need only to POST it to /create with the id and the value of that id? Thanks guys. I hope you can help me. :)
You are setting the value of req.params.id as the key, and the possibly undefined value of req.params.val as the value. You should set the req.body.val instead of req.params.val, if you are POST-ing with a request body.
Try with the following changes:
app.post('/create/:id', function (req, res) {
return client.set(req.params.id, req.body.val, function (err, data) {
if (!err) {
return res.send(data);
} else {
return console.log(err);
}
});
});
And run POST /create/123 with the body val=myValue.
Related
In my POST route, im finding two documents from my database, each one with model.findOne. Then I´m trying to take from that one of it´s key/value pair and save it into a variable.
I´ve tried window.______ method, ive tried global._____, but nothing seems to work. I´ve ignored the "var" keyword, but whatever I do, I cant access these variables anywhere else.
app.post("/match", (req, res, next) => {
Team.findOne({name: req.body.team1}, (err, team) => {
if(err) {
console.log(err);
} else {
let eloOne = team.elo; // <-- here is the problem part
}
});
Team.findOne({name: req.body.team2}, (err, team2) => {
if (err) {
console.log(err)
} else {
let eloTwo = team2.elo; // <-- here is the problem part
}
});
console.log(eloOne) // <-- here i want to use the variables
console.log(eloTwo)
}); // please dont kill me for this code, I've started programing recently
Here is the code.
app.post("/match", (req, res, next) => {
Team.findOne({name: req.body.team1}, (err, team) => {
if(err) {
console.log(err);
} else {
let eloOne = team.elo; // <-- here is the problem part
Team.findOne({name: req.body.team2}, (err, team2) => {
if (err) {
console.log(err)
} else {
let eloTwo = team2.elo; // <-- here is the problem part
console.log(eloOne) // <-- here i want to use the variables
console.log(eloTwo)
res.send(' request complete')
}
});
}
});
});
I suggest to use 'async await' or promise atleast.
Use promise.all as it will be doing both the network calls in parallel, and hence increase the performance.
app.post("/match", async (req, res, next) => {
try {
const [team, team2 ] = await Promise.all([Team.findOne({name: req.body.team1}).exec(), Team.findOne({name: req.body.team2}).exec()]),
eloOne = team.elo,
eloTwo = team2.elo;
console.log(eloOne)
console.log(eloTwo)
} catch(error) {
console.log(error);
}
});
with EXPRESS.JS i wrote a service to connect my app to a database, this service is basically an endpoint and inside i have multiple GET or POST requests.
now i have to make two different POST request on the same address.
first POST request:
app.post("/accesso", function(req, res) {
connection.getConnection(function(err, connection) {
let sql = "DELETE FROM accesso where ?";
let variabile = { idaccesso: req.body.idaccesso };
connection.query(sql, variabile, function(error, results) {
if (error) throw error;
res.send(results).end();
});
connection.release();
});
});
second POST request:
app.post("/accesso", function(req, res) {
connection.getConnection(function(err, connection) {
let sql = "INSERT INTO accesso SET ?";
let variabile = { utente: req.body.utente };
connection.query(sql, variabile, function(error, results) {
if (error) throw error;
// RISPOSTA DATABASE:
res.send(results).end();
});
connection.release();
});
});
when i test those requests obviously i can't make the post request, because basically the sql query and the body is different.
is there a way to make multiple POST request on the same TABLE?
Use the next() middleware.
The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
So, in your code, change your first post request by including the next parameter and call it once the post is made like this,
app.post("/accesso", function(req, res, next) {
connection.getConnection(function(err, connection) {
let sql = "DELETE FROM accesso where ?";
let variabile = { idaccesso: req.body.idaccesso };
connection.query(sql, variabile, function(error, results) {
if (error) throw error;
res.send(results).end();
});
connection.release();
next();
});
});
Then place your second post request as is (without any change).
Hope this helps!
As your first request want to delete something from DB, you can define a app.delete method with the same path.
And let the second method be the same as post.
app.delete("/accesso", function(req, res) {
connection.getConnection(function(err, connection) {
let sql = "DELETE FROM accesso where ?";
let variabile = { idaccesso: req.body.idaccesso };
connection.query(sql, variabile, function(error, results) {
if (error) throw error;
res.send(results).end();
});
connection.release();
});
});
I'm working on a NodeJS/Express program and I'm trying to get a POST request to return data. When I return a direct string, I get the correct response.
app.post("/DoStuff", function(req, res, Data) {
DoStuf.DoStuffFunction(req.body.UserID, function(label) {
Data = label
})
res.send({message: "Stuff"});
})
When I change it to return a variable (which is still a string) it only returns "{}".
app.post("/DoStuff", function(req, res, Data) {
DoStuf.DoStuffFunction(req.body.UserID, function(label) {
Data = label
})
res.send({message: Data});
})
Even when I make Data = "foo" the response is "{}"
You need to send from inside of callback function. In your code res.send is independent of DoStuffFunction's callback
app.post("/DoStuff", function(req, res, Data) {
DoStuf.DoStuffFunction(req.body.UserID, function(label) {
Data = label;
res.send({message: Data});
})
})
Looks like your DoStuffFunction is async. So just move res.send(..) in callback.Something like
app.post("/DoStuff", function(req, res, Data) {
DoStuf.DoStuffFunction(req.body.UserID, function(label) {
res.send({message: label});
})
})
When I change it to return a variable (which is still a string) it only returns "{}".
This is because DoStuf.DoStuffFunction(){} is asynchronous.
The reason why it works when you use stuff as value is because the operation is synchronous. And you have value with you before sending the response.
If you want to send response only after the DoStuffFunction() completes, place the response.send() within the callback.
'use strict';
app.post("/DoStuff", function(req, res, Data) {
DoStuf.DoStuffFunction(req.body.UserID, function(label) {
res.send({message: label}); //you can send label's value directly
});
});
I'm using the Express framework for my node application. I'm quite new to it so I thought I'd create a defacto "To-Do" application to learn about it. What I'm trying to do it log a request made for debugging purposes. So when I go to:
app.get('/todos/:id', function (req, res) {
var result = db.load(req.params.id);
result ? res.send(result) : res.send(404);
});
I want to a) see what result equals and b) log what happens in my db.load method:
exports.load = function (id) {
todos.findOne({ id: id }, function (err, todo) {
if (!err) {
return todo;
}
});
}
I'm using the mongolian library to access my MongoDB data. I've followed an example by Steve Sanderson: https://github.com/SteveSanderson/nodejs-webmatrix-video-tutorials
app.get('/todos/:id', function (req, res) {
db.load(req.params.id, function(err, result) {
// also handle err
result ? res.send(result) : res.send(404);
});
});
exports.load = function (id, callback) {
todos.findOne({ id: id }, callback);
}
I am working on a NodeJs project for the first time. And now i am stuck with the function returning values through JS and getting values to use in express.
var dbitems = "before fn";
function refreshData(callback) {
db.open(function (err, db) {
if (!err) {
db.collection('emp').find().toArray(function (err, items) {
dbitems = items;
callback(JSON.stringify(items));
});
}
else {
console.log("Could not be connnected" + err);
dbitems = {"value":"not found"};
}
});
}
}
refreshData(function (id) { console.log(id); });
This function retrieves values perfectly from refreshData and writes into console. But what I need is to use the retrieved value to send into express html file from this function by "returnedData"
exports.index = function (req, res) {
var valrs = refreshData(function (id) {
console.log(JSON.parse(id)); ---this again writes data perfectly in the console
});
console.log(valrs); -------------------but again resulting in undefined
res.render('index', { title: 'Express test', returnedData: valrs });
};
Any help would be appreciated.
Thanks & Regards,
Luckyy.
You need to render this after the database request finishes.. so it needs to be called from within the callback.
exports.index = function (req, res) {
refreshData(function (id) {
res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
});
};
it's asynchronous so you can't just put values in order, needs to go through the callbacks.