I am getting (this.parent.acquire is not a function) error in the following code
app.post("/add", (req,res) => {
const config = {
server: 'server', //update me
user: 'user', //update me
password: 'pass', //update me
database: 'db',
trustServerCertificate: true
}
let pool2 = sql.connect(config)
try {
const transaction = new sql.Transaction(pool2)
transaction.begin(err => {
if(err) {
console.log(err);
}
const request = new sql.Request(transaction)
request.query('insert into fsraSample (A93) values (12345)', (err, result) => {
if(err) {
console.log(err);
}
transaction.commit(err => {
if(err) {
console.log(err);
}
console.log("Transaction committed.")
})
})
})
} catch(err) {
console.log();
}
res.sendFile(path.join(__dirname + '/index.html'));
});
Whats the issue here? I am using the above code to insert some data in sql server using node js
Related
I'm trying to get result from node.js api however, whenever i deploy my website, it gets html result like below.
but it works when it's on local. but not on the deployed website.
so i tried to use axios post then it gets 404 error.
and another api is work but when i write new api then it gets error.
this is my node.js
//this post work just fine .
app.post("/insertCodeVisual", async (req, res) => {
const { data } = await req.body;
const visualData = new CodeVisualData({
data: data,
});
try {
visualData.save((err, info) => {
res.send(info._id);
});
console.log("success");
} catch (error) {
console.log(error);
}
});
//but this post is not working
app.post("/api/database", async (req, res) => {
const { host, user, password, port, table, database } = await req.body;
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
port: port,
database: database,
});
try {
connection.connect();
} catch (error) {
res.send([["ERROR_CODE"], [error.code]]);
}
const sql = `SELECT * FROM ${table}`;
connection.query(sql, function (err, results) {
if (err) {
return res.send([
["ERROR"],
[`code : ${err.code}`],
[`errno : ${err.errno}`],
[`sqlMessage : ${err.sqlMessage}`],
]);
} else {
const parse = papa.unparse(results, {
quotes: false, //or array of booleans
quoteChar: '"',
escapeChar: '"',
delimiter: ",",
header: true,
newline: "\r\n",
skipEmptyLines: false, //other option is 'greedy', meaning skip delimiters, quotes, and whitespace.
columns: null, //or array of strings
});
const unparse = papa.parse(parse);
res.send(unparse.data);
}
});
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
React.js
this one is working absolutely
const insertData = async () => {
try {
if (confirm("are u sure? ")) {
axios
.post(`${backend}/insertCodeVisual`, {
data: {
client: client,
header: header,
},
})
.then(res => {
setJustSavedDataId(res.data);
});
} else {
return;
}
} catch (error) {
console.log(error);
}
};
this below is not working when i deployed .
const getDatabase = async () => {
const url = `${backend}/api/database`;
const api = await axios.post(url, db[id]);
const data = api.data;
try {
setInfo({ ...info, [id]: data });
} catch (error) {
console.log(error);
}
};
So i wonder what cases make this kind of issue.
I'm working on the backend of my react project and I seem to be having some trouble with the backend for the info. When I do npm start I get an error saying Route.post() requires a callback function but got a [object Undefined] and I'm confused as to why.
Here is my server.js file
const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://tami00:MEUxClWqUNbLz359#cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.use('/favourite', require('.app/routes/favourite.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "creator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'creator' to roles collection");
});
new Role({
name: "watcher"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'watcher' to roles collection");
});
}
});
}
and here is my favourite.routes.js file. I have no issue with the other 2 routes.
const express = require('express');
const router = express.Router();
const{Favourite} = require("../models/favourite.model");
const {auth} = require("../middlewares/authJwt");
router.post("/favouriteNumber", auth, (req, res) => {
Favourite.find({"movieId": req.body.movieId})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
res.status(200).json({success: true, favouriteNumber: favourite.length})
})
})
router.post("/favourited", auth, (req, res) => {
Favourite.find({"movieId": req.body.movieId, "userFrom": req.body.userFrom})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
let result = false;
if(favourite.length !== 0) {
result = true
}
res.status(200).json({success: true, favourited: result});
})
})
router.post("/addToFavourite", auth, (req, res) => {
const favourite = new Favourite(req.body)
favourite.save((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
router.post("/removeFavorite", auth, (req, res) => {
Favourite.findOneAndDelete({movieId: req.body.movieId, userFrom: req.body.userFrom})
.exec((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
module.exports = router;
This is the favourite models where I'm creating the mongoose schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const favSchema = mongoose.Schema({
userFrom: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
movieId : {
type: String
},
movieTitle : {
type: String
},
movieImg : {
type: String
}
})
const Favourite = mongoose.model('Favourite', favSchema);
module.exports = {Favourite}
Heres the middlewares auth file
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;
const Role = db.role;
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized!" });
}
req.userId = decoded.id;
next();
});
};
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({ message: "Require Admin Role!" });
return;
}
);
});
};
isModerator = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles }
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}
res.status(403).send({ message: "Require Moderator Role!" });
return;
}
);
});
};
const authJwt = {
verifyToken,
isAdmin,
isModerator
};
module.exports = authJwt;
const {auth} = require("../middlewares/authJwt"); uses destructuring, but your exports from ../middlewares/authJwt don't have a field auth.
auth therefore is undefined.
I am changing my backend (switching over from Mongo to MySql). I know the error is getting thrown because a return statement is being executed before my SQL query has finished and then when my sql query finishes, it tires to send another res.send, hence why I am trying to use mysql2 with Promise wrappers to use await on queries in my async function.
I have a separate file that creates the DB connection so I can access the connection throughout my Nodejs backend:
const mysql = require('mysql2');
async function pool(){
const pool = await mysql.createPool({
host: "ip",
user: "username",
password: "password",
database: "db"
});
return pool
}
exports.getConnection = async function(callback) {
const currentPool = await pool();
currentPool.getConnection(function(err, conn) {
if(err) return callback(err);
callback(err,conn)
});
};
Then, to create a query that follows async/await:
sql.getConnection(async function(err, client){
client.query(`select email from users where email = "${email}"`, function (error, result){
if(error) return res.status(500).send('an internal db error occurred');
// carry on with code ...
});
});
I've tried using await on the query too:
await sql.getConnection(async function(err, client){
client.query(`select email from users where email = "${email}"`, function (error, result){
if(error) return res.status(500).send('an internal db error occurred');
// carry on with code ...
});
});
What am I missing? I haven't tired to use the normal mysql NPM library and make my own promise wrapper yet...
NEW CODE:
I've updated my function:
const mysql = require('mysql2');
const pool = mysql.createPool({
host: "ip",
user: "user",
password: "pass",
database: "db"
});
exports.db = (sql) => {
new Promise((resolve, reject) => {
pool.getConnection((err, conn) => {
if(err) return reject(err);
conn.query(sql, (err, results, fields) => {
conn.release()
if(err) return reject(err)
console.log(results)
resolve(results);
});
});
});
}
Then I call it via:
try{
const emailExisit = await sql.db(`SELECT email FROM users WHERE email = "${email}"`);
console.log(emailExisit);
if(emailExisit.length > 0) return res.status(422).send({"data": "", "code": "105", "message": "An account with given email already exists"});
}catch (err) {
console.log(err)
return res.status(500).send({"data": "", "code": "108", "message": `There seems to be an error contacting the database. Try again later <br> ${err}`});
}
However, my code still continues, leaving my emailExists variable undefined (yes, it is inside an async function)
This is my configuration to use MySQL with Node.js. I hope it works with you.
/config/mysql.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
port: process.env.MYSQL_PORT,
database: process.env.MYSQL_DB_NAME,
});
const query = (query, args = []) =>
new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
return reject(err);
}
connection.query(query, args, (err, results) => {
connection.release();
if (err) {
return reject(err);
}
resolve(results);
});
});
});
module.exports = { query };
/index.js
const { query } = require('./mysql');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.get('/api/v1/sum', (req, res) => {
query('SELECT 1 + 1 as sum')
.then(results => {
res.json({ sum: results[0].sum });
})
.catch(err => {
console.error(err);
res.status(500).json({ error: 'error msg' });
});
});
// anther example with async
app.get('/api/v1/sum', async (req, res) => {
try {
const results = await query('SELECT 1 + 1 as sum');
res.json({ sum: results[0].sum });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'error msg' });
}
});
app.listen(3000);
Connection.js
const mysql = require("mysql");
var mysqlConnection = mysql.createConnection({
host: "xxxxx.amazonaws.com",
user: "admin",
password: "xxx",
database: "xxx",
multipleStatements: true,
});
var connect=()=> return new Promise((resolve,reject)=>{
mysqlConnection.connect((err) => {
if (err) {
reject ("Failed to connect")
}
else{
resolve ("Connected")
}
});
})
module.exports = { mysqlConnection,connect};
server.js
app.get("/", (req, res) => {
var fetchDetail = `xxxx`
connect()
.then((result)=>{
console.log(result)
mysqlConnection.query(fetchDetail, (error, result, fields) => {
if (error) {
console.log(error);
} else {
console.log("Successfull");
res.send(result);
}
});
})
.catch((err)=>{
res.send(err)
})
}
);
If I hit the URL when the internet is closed, I want to handle the error that occurs due to connection not established and send this error as a response so I can handle it on the frontend. But what is actually happening is that my node server got crashed with the error and its not sending the err as a response.
Am I handling it in the wrong way?
What else should I do.
app.get("/", (req, res) => {
var fetchDetail = `xxxx`
connect()
.then((result)=>{
console.log(result)
mysqlConnection.query(fetchDetail, (error, result, fields) => {
if (error) {
console.log(error);
} else {
console.log("Successfull");
res.send(result);
}
});
})
.catch((err)=>{
let e=new Error("Some thing went wrong")
e.status=500;
next(e)
})
}
);
app.use(function (err, req, res, next) {
console.log(err)
res.status(500).send('Something broke!')
})
I have read the documentation how to handle error in Express from an asynchronous function.
https://expressjs.com/en/guide/error-handling.html
I'm setting up a backend server, and i want to do a put method in router.
I'm using mongoose express in backend.
When i'm trying update some data in my db with .save() , i get error:
events.js:174
throw er; // Unhandled 'error' event
^
TypeError: PC.save is not a function
I'm trying another soulution with .findOneAndUpdate(), it is success but it doesn't update my database.
const express = require('express')
const routes = express()
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true });
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", function(callback){
console.log("Connection Succeeded");
});
var PC = require("../models/PC");
//...here is my get delete etc..
This is my first solution with findOneAndUpdate
routes.put('/:id', (req, res) => {
mongoose.set('useFindAndModify', false);
PC.findOneAndUpdate(
{ 'title': req.body.title },
{ '$set': {'description': req.body.description} },
{'new': true },
function(err, PC) {
if (err) {
console.log('ERROR WHILE PUT PC');
throw (err);
} else {
console.log('Succes set');
res.status(200).send(PC)
}
}
);
})
And this is my second solution
routes.put('/:id', (req, res) => {
PC.findById(req.params.id, 'title description', function (error, pc) {
if (error) { console.error(error); }
PC.title = req.body.title
PC.description = req.body.description
console.log(PC);
PC.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true,
message: 'PC saved successfully!',
PC: req.body
})
})
})
})
module.exports = routes;
my model:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var PCSchema = new Schema({
id: Number,
brand: String,
cpu: String,
memory: Number,
type: String,
vga: String,
score: Number,
title: String,
description: String
});
var PC = mongoose.model("PC", PCSchema);
module.exports = PC;
In your first example it looks like you are finding with the wrong param, and you should be using id.
Try using findByIdAndUpdate instead:
routes.put('/:id', (req, res) => {
mongoose.set('useFindAndModify', false);
PC.findByIdAndUpdate(
req.params.id,
{ '$set': {'description': req.body.description, 'title': req.body.title} },
{'new': true },
function(err, pc) {
if (err) {
console.log('ERROR WHILE PUT PC');
throw (err);
} else {
console.log('Succes set');
res.status(200).send(pc)
}
}
);
})
In you second example, you should be calling .save on the result, not the original PC Model. You could change that to:
routes.put('/:id', (req, res) => {
PC.findById(req.params.id, 'title description', function (error, pc) {
if (error) { console.error(error); }
// Use lowercase `pc` on all these lines
pc.title = req.body.title
pc.description = req.body.description
console.log(pc);
pc.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true,
message: 'PC saved successfully!',
PC: req.body
})
})
})
})