I am trying to have a simple post function which uses bcrypt on the password passed, then stores the data in the database, however when I call the post request in postman I am getting an error. I add a console output to see what the body was showing up as, and it is just showing an empty object. Does anyone know what could be causing this? Below is my server code:
app.post('/createUser/', function(req, res) {
console.log("below is the req body");
console.log(req.body);
var pass = bcrypt.hashSync(req.body.password, salt);
var createPromise = interact.createUser(req.body.username,
pass,);
//did promise
createPromise.then(function(createResponse) {
if (createResponse.length > 0){
//this means that there was a user with that username in the db
res.json("yes");
}
else {
// otherwise, there wasn't anything in the database with this id
res.json("no");
}
}).catch(function(err) {
console.log(err);
console.log(req.body);
res.status(500).json(err);
});
});
Related
I am new to node.js. I am not sure whether it is my code or my computer system causing this problem. The localhost:3000\login refuse to connect.
My code
const http = require('http');
var server = http.createServer((req,res)=>{
body = [];
req.on('error',(err)=>{
console.log(error);
}).on("data",(chunkdata)=>{
body.push(chunkdata);
console.log(chunkdata.toString());
}).on("end",()=>{
body = Buffer.concat(body).toString();
if(req.method =="POST"){
if(req.url=="/login"){
console.log(body)
var user = JSON.parse(body);
const {username,password} = user;
res.statusCode =200;
res.setHeader("Content-Type","application/json");
res.write("Your usename is "+username +"and password is "+password );
res.end();
}
}
})
})
server.listen(3000,() => {
console.log("Server connected");
});
Can you help me solve this problem?
I try using Postman and it working fine
If you directly trying to go localhost:3000\login on your browser that means you are making a GET request but you defined /login route as POST in your code.
I am new to both node and express so I figure I am doing something stupid.
Complete source code can be found at:
https://github.com/wa1gon/aclogGate/tree/master/server
logRouter.get("/loggate/v1/listall", function(req, res) {
let countStr = req.param('count');
let count: number;
if (!countStr) {
count = null;
} else {
count = Number.parseInt(countStr);
if (count == NaN) count = null;
}
acConn.listAllDatabase(count, (err: string, result: Array<LogGateResp>) => {
console.log("got list all data resp")
return res.json(result).end();
});
}
);
app.use('/', logRouter);
It works the first time though, but blows up the second.
listallDatabase connects to a network socket which gets XML database back, parses it and calls back with an JS object. Which in turn calls res.json.
Suggestions?
Remove the end() after res.json().
res.josn() send the response to frontend and end() try to send the response again.
That why you are getting the error. Because node.js don't allow the API to send response twice. Either use res.end() or res.json().
Im doing a RESTful server on NodeJS and MongoDB but im stuck on the DELETE method, because im getting the error
"Argument passed in must be a single String of …modules\express\lib\router\index.js:174:3"
when trying to cast the req.body.listId into an ObjectId.
Here's my code:
router.delete('/', function(req, res){
var db = req.db;
var collection = db.get('listcollection');
var oId = new ObjectId(req.body.listId); //The exception is here
collection.remove(
{
"_id": oId
},function(err,doc){
if (err) {
res.json("There was a problem deleting the information to the database.");
}
else {
res.json("Successfully deleted");
}
}
);
});
Solved!:
The listId parameter was quoted ("58f8b2cc8cf726ca76551589") so I did an slice. Anyway I changed the param to be received in the URL, here's the code: Thanks!!
router.delete('/:listId', function(req, res){
var db = req.db;
var collection = db.get('listcollection');
var listId = req.params.listId;
listId = listId.slice(1, listId.length - 1);
var oId = new ObjectId(listId);
collection.remove(
{
"_id": oId
},function(err,doc){
if (err) {
res.json("There was a problem deleting the information to the database.");
}
else {
res.json("Successfully deleted");
}
}
);
});
The error happens because req.body.listId does not follow the rule of ObjectId -- ObjectId is a string of 12 bytes (24 0-9 or a-f characters, e.g. "507f1f77bcf86cd799439011"). What may go wrong is:
req.body.listId is a plain number, not a String type, e.g. 89876.
req.body.listId is a String, but not follow the rule described above.
Although it is not RESTful, HTTP DELETE request with JSON body is totally OK. The Node.js server can receive the request and its body.
I have an Express post route which updates a mongo db based on data sent to it from a DataTables Editor inline field. So far so good and the database is updating fine. Where it falls over is after the update query executes successfully and I want to then redirect back to the originating page. The Node console seems to indicate that the GET route to the originating page is being called, but the page itself doesn't load.
The code for the POST function is as follows:
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
The GET route works fine when called directly, but seems to halt when called like this.
I'm pretty sure that there's nothing in the POST route that is causing this as the same thing happens when I strip out everything except the redirect itself.
router.post('/test',function(req,res){
res.redirect('/admin');
});
Please help!
I am trying to connect my Unity app to a RESTful API I wrote using Javascript and MySQL. At the moment I am having an issue with the unity code which is calling one of my API endpoints - it seems like the Unity code is not connecting to the server at all.
Here is the server endpoint for reference:
app.post("/api/users/authenticate/", function(req, res) {
var queryString = `SELECT UserID, Password FROM UserAccount WHERE UserName = ?`;
console.log("test");
console.log(req.body.UserName);
console.log(req.body.Password);
connection.query(queryString, [req.body.UserName], function(err, resp) {
if (!resp[0]) {
res.send("ER_INCORRECT_USERNAME");
} else {
var string = JSON.stringify(resp);
var jsonResp = JSON.parse(string);
if (jsonResp[0].Password == req.body.Password) {
res.send(jsonResp[0].UserID.toString());
} else {
res.send("FAILURE_AUTHENTICATED");
}
}
});
connection.end;
});
You can see that this endpoint simply checks to see if the provided parameters are the same as the ones stored in the MySQL database so as to authenticate a player account. Take note of the console.log statements.
Here is the unity code that I am trying to use to POST to this endpoint:
public static class PlayerAccountsInterface
{
public static IEnumerator AuthenticatePlayer(String username, String password)
{
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("UserName", username));
form.Add(new MultipartFormDataSection("Password", password));
UnityWebRequest request = UnityWebRequest.Post(InterfaceTools.GetAccountsUrl("authenticate"), form);
request.SetRequestHeader("Accept", "application/json");
yield return request.Send();
}
}
The function InterfaceTools.GetAccountsUrl simply gets the IP address and URL of the server endpoint. This part is definitely correct. The server endpoint is also correct as I've tested it independently using POSTman.
When I run the unity code, no call is being made to the server endpoint. I know this because the three console.log() statements are not triggered.
What could be causing this issue?