i really don't know what it could be a problem but everytime i try to post i get a log error : ER_BAD_NULL_ERROR: Column 'idmedecin' cannot be null
i've seen allot of similar questions (trouble in post req) but nothing solved my problem and i cannot see what im doing wrong since idmedcin is clearly not NULL
reqLink used = http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pim',
multipleStatements: true
});
mysqlConnection.connect((err) => {
if (!err)
console.log('DB connection succeded.');
else
console.log('DB connection failed \n Error : ' + JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is runnig at port no : 3000'));
app.post('/rendezvousinsert/',(req,res)=> {
var post= {
idmedecin : req.body.idmedecin ,
idpatient : req.body.idpatient ,
date : req.body.date ,
etat : req.body.etat
};
mysqlConnection.query('INSERT INTO rendezvous SET ?' , post, function(error) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
});
here is my table structure
You're sending data through query string http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1 but trying to access it through req.body
idmedecin=1&idpatient=1&date=546654&etat=1 This data is available as
req.query.idmedecin // 1
req.query.idpatient // 1
req.query.date // 546654
// etc
You are trying to get the fields from the request body, but in your example you send them as query params.
I think the correct way is to send the object inside the POST body and not as query params, but if you want the request to remain as in your example, it should look like this:
var post= {
idmedecin : req.query.idmedecin ,
idpatient : req.query.idpatient ,
date : req.query.date ,
etat : req.query.etat
};
Related
I unknowingly sent a request twice with the same insert query which led to the same record being added twice. now when I'm trying to use the delete statement it's showing 'sending request' and is not moving forward.
but the delete statement is working if I try n delete any other record with does not have duplicate values. eg-
if I try using the delete statement on the record having request 1001, it isn't working, as there are 2 records with the same request_id.
but if I try to delete the record with the request id 1002, its working.
this is my code-
var express=require('express');
var router=express.Router();
var oracledb=require('oracledb');
router.post('/ins-rpt',function(req,res,next){
//get the data from req
const {stat,rid,rptcomp,reqr}=req.body;
//connect with db
var connectionString="(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)
(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER
= DEDICATED)(SERVICE_NAME = orcl))"
oracledb.getConnection(
{
user: 'system',
password:'Valli1234',
tns:connectionString
}, async function(err,con){
if(err){
res.status(500).json({
message : 'not connected'
})
}
else{
//reqd opn
var q="delete from rpt where request_id=:1";
//send response
await con.execute(q,[],
{autoCommit:true},function(e,s){
if(e){
res.status(500).json({
message : e
})
}
else
{
res.status(200).json({
message : s
})
}
})
}
});
})
module.exports=router;
I am trying to get SharePoint list items from Node.js app but I am still getting following error:
No XML to parse!
at new XmlDocument (C:\Users\xx\Desktop\AppTest2\node_modules\xmldoc\lib\xmldoc.js:247:11)
at C:\Users\xx\Desktop\AppTest2\node_modules\node-sp-auth\lib\src\utils\AdfsHelper.js:28:25
at processTicksAndRejections (node:internal/process/task_queues:96:5)
As you may see, I tried it with 'node-sp-auth' and 'sp-request' but result is the same.
Could it be some security or network related issue or do I miss something?
I tried the same http request via power automate and it was working.
Thanks for your help in advance.
var express = require('express');
var app = express();
const port = process.env.PORT || 3000;
//sharepoint auth libs
var spauth = require('node-sp-auth');
var request = require('request-promise');
var $REST = require("gd-sprest");
var url = "https://inoffice.sharepoint.com/sites/";
const credentialOptions =
{
username: "xx",
password: "oxxVMQOz",
online: true
};
const credentialOptions2 =
{
username: "yy",
password: "xxx",
online: true
};
var sprequest = require('sp-request');
let spr = sprequest.create(credentialOptions);
spr.get('https://inoffice.sharepoint.com/sites/DEV/_api/web/lists/GetByTitle(\'Users\')')
.then(response => {
console.log('List Id: ' + response.body.d.Id);
})
.catch(err =>{
console.log(err);
});
/*
spauth.getAuth(
url,
{
username: "WW_DEV_AAPeople_Mgmt#emea.adecco.net",
password: "oq&a#Dl59XVMQOz",
online: true
}
).then(options => {
// Log
console.log("Connected to SPO");
// Code Continues in 'Generate the Request'
});
*/
I'm working on a REST API Get request to insert new data with multiple parameters into a SQL database, but it doesn't work. Here is my code:
var express = require('express'); // Web Framework
var app = express();
var sql = require('mssql'); // MS Sql Server client
const { request } = require('http');
// Connection string parameters.
var sqlConfig = {
user: 'username',
password: 'password',
server: 'serveraddress',
database: 'databasename'
}
// Start server and listen on http://localhost:8081/
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("app listening at http://%s:%s", host, port)
});
app.get("/item/insert/:name/:category/:color/:description/:numberOfUsage/:size/:status", function(req , res){
console.log(req.params)
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = "INSERT INTO dbo.Item (name, category, color, description, numberOfUsage, size, status) VALUES ("+ req.query.name +","+ req.query.category+","+ req.query.color+","+ req.query.description+","+req.query.numberOfUsage+","+req.query.size+","+req.query.status+" )";
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
});
});
})
If i try to insert a new item via browser like "http://localhost:8081/item/insert/MyNewShirt/Shirt/Red/Thatsmynewshirt/1/L/1" returns always status 200 - OK, but the IDE console prints the "RequestError: Invalid column name 'undefined'."
What its mean? How solve it?
Because you're directly accessing params value to it's name like
In Express you need to get query string variables via req.query like this for all params. like in this query
INSERT INTO dbo.Item (name, category, color, description, numberOfUsage, size, status) VALUES ("+ req.query.name +","+ req.query.category+","+ req.query.color+","+ req.query.description+","+req.query.numberOfUsage+","+req.query.size+","+req.query.status+" )"
change all values like shows below
var name = req.query.name;
Otherwise, in NodeJS, you can access req.url and the builtin url module to [url.parse]
(https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost) it manually:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
I found a solution. First the new code:
app.get("/item/insert/:name/:category/:color/:description/:numberOfUsage/:size/:status", function(req , res){
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = "INSERT INTO dbo.Item (name, category, color, description, numberOfUsage, size, status) VALUES ('"+ req.params.name +"','"+ req.params.category+"','"+ req.params.color+"','"+ req.params.description+"','"+req.params.numberOfUsage+"','"+req.params.size+"','"+req.params.status+"')";
console.log(stringRequest)
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
});
});
})
The only two things I had to change were:
Parameters: 'req.query' to 'req.params'
SQL Statement: Instead of using " just using ' to close the VALUES
i created a node.js code that listen to sql server and access it database and im trying to run the code on browser using "http://localhost:1433/test" but it always giving men this
this is my node.js code:
const uid = require('uuid');
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const driver = require('msnodesqlv8');
const config = {
// multipleStatements: true, TO EXECUTE MORE THAN ONE QUERY IN ONE STATEMENT
//driver: 'msnodesqlv8',
server: 'MOSTAFA',
user: 'admin',
password: 'mostafabaron123#',
database: 'WholeSale',
options:{
trustedConnection: true,
useUTC: true,
}
};
const userExistCode = 200;
const buyerCreatedCode = 400;
const buyerNotCreatedCode = 401;
const sellerCreatedCode = 500;
const sellerNotCreatedCode = 501;
const connectionErrCode = 100;
var app = express();
app.use(bodyParser.json()); // accept JSON parms
app.use(bodyParser.urlencoded({extended:true}));
// bueyer signup part
app.post('/buyerSignUp', function(req, res) {
var postData = req.body; // get post params
var userId = uid.v4();
sql.connect(config, (err)=>{
if(err){
console.log('not connected');
return;
}
var request = new sql.Request();
request.input('email', sql.VarChar(45), postData.email)
.input('password', sql.VarChar(45), postData.password)
.input('category', sql.VarChar(45), postData.category)
.query('select * from Buyer where email = #email and category = #category
and password = #password'
, (err, recordSet)=>{
if(recordSet.length == 1){
res.status(userExistCode).send("Buyer already exists.");
}else{
new sql.Request()
.input('buyerId', sql.VarChar(45), userId)
.input('firstName', sql.VarChar(45), postData.firstName)
.input('lastName', sql.VarChar(45), postData.lastName)
.input('email', sql.VarChar(45), postData.email)
.input('password', sql.VarChar(45), postData.password)
.input('phoneNumber', sql.VarChar(45), postData.phoneNumber)
.input('category', sql.VarChar(45), postData.category)
.query('insert into Buyer(buyer_id, first_name, last_name, email,
password, phone_number, category) values(#buyerId, #firstName,
#lastName, #email, #password, #phoneNumber, #category)'
, (err, recordSet)=>{
if(err){
console.log(err);
return;
}
if(recordSet.length == 1){
res.status(buyerCreatedCode).send("Account Created as Buyer.");
}else{
res.status(buyerNotCreatedCode).send("Account not Created as
Buyer.");
}
});
}
});
});
});
app.listen(1433, ()=>{
console.log('server is running on 1433...');
});
what i expect to see the messages if the user created or already existed.
anyone can explain why this is happening?
Just from reading your code, here is what I suspect is happening: you are starting up express and listening to port 1433. It does successfully call your listening callback and print the appropriate console.log statement, so we know it gets that far.
Then, you attempt to connect to your database. Your database port is also 1433, which we know is not correct (the database port cannot be the same as your express port, if it was, express would never have started). So your connection to the database fails.
The database connection callback checks for an error, then returns. This means you'll never see the "connected" console.log statement, and you'll never actually create the route for /buyerSignup. Basically, your app is running, but has no useful routes.
(I'm not sure what you even expect to see at the URL /test -- nothing in this code snippet shows you creating that route. But, you'll need to fix the issues above in any case.)
I'm making a call to the server using resource and when I go to the base URL of
/viewEvent
It works fine. I receive all the database entries. However, when I go to
/viewEvent/1234
where 1234 is the eventID
I get a undefined is not a function and this is a crash from within angular. Stack trace is
TypeError: undefined is not a function
at copy (http://localhost:8000/js/lib/angular/angular.js:593:21)
at http://localhost:8000/js/lib/angular/angular-resource.js:410:19
at wrappedCallback (http://localhost:8000/js/lib/angular/angular.js:6846:59)
at http://localhost:8000/js/lib/angular/angular.js:6883:26
at Object.Scope.$eval (http://localhost:8000/js/lib/angular/angular.js:8057:28)
at Object.Scope.$digest (http://localhost:8000/js/lib/angular/angular.js:7922:25)
at Object.Scope.$apply (http://localhost:8000/js/lib/angular/angular.js:8143:24)
at done (http://localhost:8000/js/lib/angular/angular.js:9170:20)
at completeRequest (http://localhost:8000/js/lib/angular/angular.js:9333:7)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/js/lib/angular/angular.js:9303:11) angular.js:575
When I examine the server, the request was made correctly. I can see that it got 1234 and it pulls the correct entry from the mongo database.
This is the controller logic
.controller("viewEventsController", ["$scope", 'EventService', '$location', function($scope, EventService, $location){
var path = $location.path().split('/');
var pathSize = path.length;
$scope.events = [];
if(pathSize === 2){
console.log("No event ID");
$scope.events = EventService.query();
}
else{
console.log("Event ID specified");
EventService.get({"eventID": path[pathSize - 1]}, function(data){
//$scope.events.push(data);
console.log(data);
}, function(error){
console.log(error);
});
}
}]);
and the service logic
service.factory('EventService', function($resource){
return $resource('api/viewEvent/:eventID');
});
It never makes it back to the controller so I'm "confident" it's not that. (watch it be that)
Not sure if the best way, but I got it working by doing
In service:
service.factory('EventService', function($resource){
return $resource('api/viewEvent/:eventID',
{eventID:"#eventID"},
{
'getSingleEvent': {
url: "api/viewEvent/:eventID",
method: "GET",
isArray: true
}
}
);
controller
var path = $location.path().split('/');
var pathSize = path.length;
EventService.getSingleEvent({"eventID":path[pathSize - 1]}, function(result){
$scope.updateEvent();
});
Server
routes = require('./routes')
var router = express.Router();
router.get('/api/viewEvent/:eventID', routes.viewEvent);
and in the routes directory I have a js file with
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'eventApp');
var eventSchema = require('../models/createEvent.js').eventSchema;
var event = db.model('events', eventSchema);
exports.viewEvent = function(req, res){
console.log(req.params.eventID);
if(req.params.eventID) {
event.find({"_id": req.params.eventID}, function (error, events) {
console.log(events);
res.send(events);
});
}
else{
event.find({}, function (error, events) {
console.log(events);
res.send(events);
})
}
};