Cannot add a correct invoice using ReactJS - javascript

I developped an invoice using ReactJS, nodejs and mysql, it have a dynamic table, as you can see the invoive component in this link : https://codeshare.io/5zqLeN
My router is :
exports.ajouterfact = function(req, res) {
console.log("req", req.body);
var today = new Date();
var factures = {
"Nfact": req.body.Nfact,
"Nom": req.body.Nom,
"Datefact": req.body.Datefact,
"Note": req.body.Note,
"Nomp": req.body.Nomp,
"QuantiteF": req.body.QuantiteF,
}
connection.query('INSERT INTO factures SET ?', factures, function(error, results, fields) {
if (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
else {
// console.log('The solution is: ', results);
res.send({
"code": 200,
"success": "facture registered sucessfully"
});
}
})
};
My invoice is :
When I submit it, It will be added on the database by getting:
req { Nfact: '15',
Nom: 'Imen',
Datefact: '2018-09-04T09:47:32.925Z',
Note: 'Test',
QuantiteF: '' }
The Noun of product (Nomp) is null and the quantity is ''.
But when I run my backend with Postman, it works well.
How can I fix that ?

Related

need Mongoose Model.find() to work when queries aren't present

I'm currently working on the freeCodeCamp Exercise Tracker Project on Replit.
my Project Link: https://replit.com/#mazorSharp/Exercise-Tracker?v=1
If you click on the link, the code I'm referring to is in the server.js file and It's the code under the comment labeled // NUMBER 3
I'm running into an issue with one of the GET routes.
GET user's exercise log: GET /api/users/:_id/logs?[from][&to][&limit]
The GET route works fine when all queries are used in the get search. Queries for the test are From, To, and Limit. If one of the queries aren't present in the GET request I get an error.
CastError: Cast to date failed for value "Invalid Date" (type Date) at path "date" for model "exerciseInfo"
What steps would I need to take to make sure if someone isn't putting in values for FROM, TO, and LIMIT queries that it wouldn't throw an error because of it?
app.get('/api/users/:_id/logs', (req, res) => {
const {from, to, limit} = req.query;
let idJson = {"id": req.params._id}
let idToCheck = idJson.id;
console.log("from=> ", from, "to=> ", to, "limit=> ", limit, "idToCheck=> ", idToCheck);
//Check ID
ExerciseInfo.findById(idToCheck, (err, data) => {
if (err) {
console.log("Error with ID => ", err);
} else {
// Find Username Documents
ExerciseInfo.find(({username: data.username}, {date: {$gte: new Date(from), $lte: new Date(to)}}), null , {limit: +limit} , (err, doc) => {
let loggedArray = []
if (err) {
console.log("error with username=> ", err);
} else {
console.log("all docs related to username=> ", doc);
let documents = doc;
let loggedArray = documents.map((item) => {
return {
"description": item.description,
"duration": item.duration,
"date": item.date.toDateString(),
}
})
const test = new LogInfo({
// "_id": idToCheck,
"username": data.username,
"from": from,
"to": to,
"count": limit,
"log": loggedArray,
})
test.save((err, data) => {
if (err) {
console.log(err);
} else {
console.log("saved exercise successfully")
res.json({
"_id": idToCheck,
"username": data.username,
"from": data.from.toDateString(),
"to": data.to.toDateString(),
"count": data.count,
"log": loggedArray,
})
}
})
}
})
}
})
})

How to return the response of a express server to change the value of a html checkbox to a js file that manages the HTML?

So Im making a log-in where, if the user and password are correct, a checkbox's value becomes true, everything is done, but I dont know how to return the value from the server using the response from express. Here is the POST methon in the server:
app.post('/CTRL', function (req, res) {
var nombre = req.body.name;
var passw = req.body.passw;
connection.query('SELECT * FROM usuario WHERE User=?', [nombre], function (error, results, fields) {
if (error) {
res.send({
"code": 400,
"failed": "error ocurred"
})
} else {
if (results.length > 0) {
if (results[0].Password == passw) {
console.log('Nombre: ' + nombre + ' password: ' + passw);
console.log('inicio de sesion exitoso!')
res.send('Nombre: ' + nombre + ' password: ' + passw);
}
else {
console.log('Contrasena incorrecta')
res.send({
"code": 204,
"success": "Email and password does not match"
});
}
}
else {
console.log('Nombre invalido');
res.send({
"code": 204,
"success": "nombre incorrecto"
});
}
}
});
});
You can return a json object with a boolean in it, and then you can set the checkbox value to that.
res.end(JSON.stringify({ loggedInSuccessfully: true }));
You should use send method like you do it with error handling:
res.send({
"code": 200,
"success": "Login is OK",
"auth": true
});
Also please see this article to learn about difference between send/json/end

401 - unauthorized access : Auth0 and azure

I have connected my Database to auth0 and when I try the connection is returns 401 unauthorized access. I have allowed auth into my firewall and the password is correct. How come it is returning this error when searching for username and password?
More info
in my easy tables I made them authenticated access only, do I have to do something to get around this?
function login(email, password, callback) {
//this example uses the "tedious" library
//more info here: http://pekim.github.io/tedious/index.html
var Connection = require('tedious#1.11.0').Connection;
var Request = require('tedious#1.11.0').Request;
var TYPES = require('tedious#1.11.0').TYPES;
var connection = new Connection({
userName: 'username',
password: 'pass',
server: 'server',
options: {
database: 'db',
encrypt: true,
rowCollectionOnRequestCompletion: true
}
});
var query = "SELECT Id, Email, Password " +
"FROM user WHERE Email = #Email";
connection.on('debug', function (text) {
// Uncomment next line in order to enable debugging messages
// console.log(text);
}).on('errorMessage', function (text) {
console.log(JSON.stringify(text, null, 2));
return callback(text);
}).on('infoMessage', function (text) {
// Uncomment next line in order to enable information messages
// console.log(JSON.stringify(text, null, 2));
});
connection.on('connect', function (err) {
if (err) { return callback(err); }
var request = new Request(query, function (err, rowCount, rows) {
if (err) {
callback(new Error(err));
} else if (rowCount < 1) {
callback(new WrongUsernameOrPasswordError(email));
} else {
bcrypt.compare(password, rows[0][2].value, function (err, isValid) {
if (err) { callback(new Error(err)); }
else if (!isValid) { callback(new WrongUsernameOrPasswordError(email)); }
else {
callback(null, {
user_id: rows[0][0].value,
email: rows[0][1].value
});
}
});
}
});
request.addParameter('Email', TYPES.VarChar, email);
connection.execSql(request);
});
}
Since you are using Azure Mobile App, which included the Node.js server SDK for your app. Then you don't need to install tedious to work with Azure SQL database. The SDK has already wrapped up mssql to do this. So basically you can use this code sample to connect your database.
var api = {
// an example of executing a SQL statement directly
get: (request, response, next) => {
var query = {
sql: 'UPDATE TodoItem SET complete = #completed',
parameters: [
{ name: 'completed', value: request.query.completed }
]
};
request.azureMobile.data.execute(query)
.then(function (results) {
response.json(results);
});
},
// an example of executing a stored procedure
post: (request, response, next) => {
var query = {
sql: 'EXEC completeAllStoredProcedure #completed',
parameters: [
{ name: 'completed', value: request.query.completed }
]
};
request.azureMobile.data.execute(query)
.then(function (results) {
response.json(results);
});
}
};
module.exports = api;
For more information, please refer to this documentation.

Sending email in zimbra using JS-Zimbra error

I'm trying to do a search quest using js-zimbra module, i keep on getting an error that i didn't knew how to fix,
her's my code :
var z = require('js-zimbra');
var comm = new z.Communication({
url: "myzimbraurl/service/soap"
});
// Authenticate
comm.auth({
"username": "user",
"secret": "pass",
"isPassword": true
}, function(err) {
if (err) {
// An error occured authenticating!
}
console.log('done !')
// Now, carry on creating requests and sending them
comm.getRequest({}, function(err, req) {
if (err) {
// Can't create a new request
}
req.addRequest({
name: "SearchRequest",
namespace: "zimbraMail",
params: {
"SearchRequest" : {
"types" : "message",
"fetch" : "all"
},
"query": {
"_content": "in:inbox"
}
}
}, function(err) {
if (err) {
console.log('err', err);
}
comm.send(req, function(err, res) {
if (err) {
console.log('err', err);
}
console.log(res);
})
})
})
});
and when i execute i got the following error message :
error: Received server error: {"Code":{"Value":"soap:Receiver"},"Reason":{"Text":"error while proxying request to target server: Connection reset"},"Detail":{"Error":{"Code":"service.PROXY_ERROR","Trace":"","_jsns":"urn:zimbra"}}}
Is there any fix for such error ?

Express/mongoose put req.body issue?

On localhost this works fine, but I when I put it on the live server the put requests are not sticking to the database. Specifically with req.body I have to define the attribute I want to send {points: req.body.points}
update: function(req, res) {
console.log("PUT received: " + req.body.points);
models.Player.update({ _id: req.params.pid }, req.body, function(err, player) {
if (err) {
res.json({error: 'Player not found.'});
} else {
res.json(player);
}
});
},
The only way I can get the above to work on the live server is, if I write the object to update like below. This is not good because the app updates more than just points, it may send a put to update {player_name: req.body.player_name} you know what I mean.
I don't understand why req.body isn't working, it usually does!!
update: function(req, res) {
console.log("PUT received: " + req.body.points);
models.Player.update({ _id: req.params.pid }, {points: req.body.points}, function(err, player) {
if (err) {
res.json({error: 'Player not found.'});
} else {
res.json(player);
}
});
},
EDIT: My quick solution was to do this, but I would rather just use the req.body object, whats the reason it's not working?
update: function(req, res) {
var test = {
player_name : req.body.player_name,
player_picture : req.body.player_picture,
bench : req.body.bench,
points : req.body.points,
rebounds : req.body.rebounds,
steals : req.body.steals,
blocks : req.body.blocks,
fouls : req.body.fouls,
team_id : req.body.team_id,
}
models.Player.update({ _id: req.params.pid }, test, function(err, player) {
if (err) {
res.json({error: 'Player not found.'});
} else {
res.json(player);
}
});
},

Categories