I am working on a full stack development using Angular, Node and mySQL. I have to send an index number of a list that the user clicks on an HTML, to a node.js where then, I will have to delete that index row from mySQL. However, I am getting an unusual error. This is my code:
HTML
<tbody *ngFor = "let db of dbData" >
<tr>
<td>{{+db.idoffice + +1}}</td>
<td>{{db.ProjectName}}</td>
<td>{{db.FiscalYear}}</td>
<td>{{db.TaskDescription}}</td>
<td>{{db.ConcernedDepartment}}</td>
<td>{{db.ActivityType}}</td>
<td>{{db.Quarter}}</td>
<td>{{db.kra}}</td>
<td>{{db.CurrentStatus}}</td>
<td>{{db.ResourceName}}</td>
<td>{{db.Notes}}</td>
<td><button class = "btn btn-success nc-icon nc-refresh-69" name="button"></button></td>
<td><button class = "btn btn-danger nc-icon nc-simple-delete" name="button" (click) =
"onDeletePosts(db.idoffice)"></button></td>
</tr>
</tbody>
Angular
private onDeletePosts(delData)
{
this.http.delete('http://localhost:3000/del', delData)
.subscribe(responseData => {
console.log(responseData);
});
}
Node.js
router.delete("/del", (req, res) => {
var del = req.body.delData;
console.log(del);
mysqlConnection.query("DELETE FROM office WHERE idOffice == ?", del , (err, results) => {
if(!err)
{
res.send(results);
}
else
{
console.log("Error occured while deleting" + err.message);
}
})
})
This is the error that I am getting:
undefined //somehow the data from angular to node isn't being received
Error occured while deletingER_PARSE_ERROR: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near '== ?' at line 1
Angular HttpClient's delete method does not take a body in it's argument. Instead you could send the ID as an URL query parameter.
Angular
import { HttpClient, HttpParams } from '#angular/common/http';
private onDeletePosts (delData: any) {
const params = new HttpParams().set('id', delData);
this.http.delete('http://localhost:3000/del', { params }).subscribe({
next: responseData => { console.log(responseData); },
error: error => { console.log(error); }
});
}
Node.js
router.delete("/del", (req, res) => {
var id = req.query.id;
console.log(id);
mysqlConnection.query("DELETE FROM office WHERE idOffice == ?", id, (err, results) => {
if (!err) {
res.send(results);
} else {
console.log("Error occured while deleting" + err.message);
}
})
})
It says there's something wrong with the query syntax.
The comparison operator you used is "==". There is no double equal in MySQL, so it's supposed to be "="
Angular
private onDeletePosts(del_id)
{
this.http.delete(`http://localhost:3000/del/${del_id}`)
.subscribe(responseData => {
console.log(responseData);
});
}
node.js
router.delete("/del/:del", (req, res) => {
const { del } = req.params;
console.log(del);
mysqlConnection.query("DELETE FROM office WHERE idOffice == ?", del, (err, results) => {
if (!err) {
res.send(results);
}
else {
console.log("Error occured while deleting" + err.message);
}
})
})
Related
I have the following mongoose "update" path:
app.put('/update', async (req, res) => {
const newTaskName = req.body.todoName
const newDays = req.body.days
const id = req.body.id
try {
await TodoModel.findById(id, async (err, updatedTodo) => {
updatedTodo.todoName = newTaskName
updatedTodo.daysToDo = newDays
await updatedTodo.save()
res.send("updated")
})
} catch(err) {
console.log(err)
}
})
Separately I have a path that returns all data from the Mongo table:
app.get('/read', async (req, res) => {
TodoModel.find({}, (err, result) => {
if (err) {
res.send(err)
}
res.send(result)
})
})
How can I both update and send back the full updated list within the response?
Separate question, not necessary to answer, but would be nice - perhaps this approach is all wrong? some background:
In my MERN app I am calling to add an item to a list and then want to immediately render the updated list as currently read from the database, since I don't want to assume the insertion was successful
I tried using some asynchronous workarounds with no luck
Fixed!
Upon further inspection of Mongoose documentation, I found that by using the findOneAndUpdate method instead of findById, I am able to utilize a callback that will return the updated item:
app.put('/update', async (req, res) => {
const id = req.body.id
let updateSet = req.body
delete updateSet.id
try {
ShoppingModel.findOneAndUpdate({ _id: id }, { $set: updateSet }, { new: true }, (err, doc) => {
if (err) return console.log(err)
res.send(doc)
})
} catch (err) {
console.log(err)
}
})
Is it possible to change the pool config database?
I have a rest API with node/express, and I have multiple databases.
So I need that when a user.company login in my frontend, the API rest, choose the database that user should use.
My configuration file for the bank is this .env
JWT_KEY=XXXXXXX
POOL1_USER=root
POOL1_PASSWORD=xxxxxx
POOL1_DATABASE=data1
POOL1_HOST=host.domain.com
POOL1_PORT=3306
Meu arquivo db.js é este:
const mysql = require("mysql");
const pool1 = mysql.createPool({
connectionLimit: 10,
user: process.env.POOL1_USER,
password: process.env.POOL1_PASSWORD,
database: process.env.POOL1_DATABASE,
host: process.env.POOL1_HOST,
port: process.env.POOL1_PORT,
});
module.exports = { pool1 };
Is this my controllers.js file?
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I need to dynamically change the database, as I have the same frontend for the same rest API, but I have multiple databases that can even be on different hosts.
It may be that what I'm trying to implement is not possible, so does anyone have any different suggestions?
Before you use the query to select a table from a database, you need to switch the database, use this query to achieve that.
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
then after it use the query that you want like this
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I can't seem to get my head around this. I have a connection set up correctly and am able to, from the frontend, get data from my database but am having trouble with some syntax I believe. I have user input being stored in "searchTerm" that I am trying to run a query against using a placeholder ?.
The code I am having trouble with is
app.get('/api/get', (req, res)=> {
const searchTerm = req.body.searchTerm;
const sqlSelect = "SELECT * FROM questions WHERE MATCH(questionTitle) AGAINST(?)";
db.query(sqlSelect, searchTerm, (err, result) => {
res.send(result);
});
});
The issue isn't with the query because it turns out a positive result in workbench and also works properly when I hardcode the user inputted value. I'm getting an Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?)'
I'm stumped because this is what I have for a post and it works as expected:
app.post('/answer/insert', (req, res, next)=> {
const question = req.body.question;
const answer = req.body.answer;
const category = req.body.category;
const today = req.body.today;
const sqlInsert = "INSERT INTO questions (questionTitle, questionBody, category, questionDate) VALUES (?,?,?,?)";
db.query(sqlInsert, [question, answer, category, today], (err, result) => {
console.log(err);
});
});
UPDATE: Frontend looks like this
function startSearch(e) {
e.preventDefault();
console.log(searchTerm);
Axios.get('http://localhost:3001/api/get', {
searchTerm: searchTerm,
})
.then(function(response) {
console.log("It worked, response is: ", response)
}).catch(function() {
console.log("error");
});
};
My post request works and it looks like this:
const submitReview = () => {
Axios.post('http://localhost:3001/answer/insert', {
question: question, answer: answer, category: category, today: today,
}).then(()=> {
console.log(category + question + answer + today);
alert('successful insert');
})
.catch(()=> {
console.log(category + question + answer + today);
alert('it didnt work');
})
}
Original Answer
As described here https://www.npmjs.com/package/mysql#performing-queries, the query parameters need to be passed in as an array.
Change
db.query(sqlSelect, searchTerm, (err, result) => {
res.send(result);
});
to
db.query(sqlSelect, [searchTerm], (err, result) => {
res.send(result);
});
Update
Your frontend called startSearch uses a GET request. This will not send anything in the body. I would use a query string (changed from parameter, a query parameter is something after a ? at the end of a URL). Assuming you are using Express.JS, take a look here https://stackabuse.com/get-query-strings-and-parameters-in-express-js/. It should point you in the right direction.
If you need specific code, this will do what you want. The above link will help you understand how this works.
Change the backend from
app.get('/api/get', (req, res)=> {
const searchTerm = req.body.searchTerm;
const sqlSelect = "SELECT * FROM questions WHERE MATCH(questionTitle) AGAINST(?)";
db.query(sqlSelect, searchTerm, (err, result) => {
res.send(result);
});
});
to
app.get('/api/get/:searchTerm', (req, res)=> {
const searchTerm = req.params.searchTerm;
const sqlSelect = "SELECT * FROM questions WHERE MATCH(questionTitle) AGAINST(?)";
db.query(sqlSelect, [searchTerm], (err, result) => {
res.send(result);
});
});
and the frontend from
function startSearch(e) {
e.preventDefault();
console.log(searchTerm);
Axios.get('http://localhost:3001/api/get', {
searchTerm: searchTerm,
})
.then(function(response) {
console.log("It worked, response is: ", response)
}).catch(function() {
console.log("error");
});
};
to
function startSearch(e) {
e.preventDefault();
console.log(searchTerm);
Axios.get('http://localhost:3001/api/get/' + searchTerm)
.then(function(response) {
console.log("It worked, response is: ", response)
}).catch(function() {
console.log("error");
});
};
I'm getting req.file as undefined. I have tried everything. I have searched for other solutions, but it's not a problem in input name="avatar" attr and upload.single("avatar").
Also, I'm getting an error in the console:
Error for image upload 400 - Bad Request
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '?)' at line
1","sqlState":"42000","index":0,"sql":"INSERT INTO avatars (image)
VALUES(?)"}
I would say that it is because req.file is undefined.
Please, help me to understand what I'm doing wrong.
api.js:
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./assets/images/uploads");
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({
storage: storage,
limits: {fileSize: 1000000},
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
});
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(file.originalname.toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if(extname && mimetype) {
return cb(null, true);
} else {
cb('Error: Images only');
}
}
router.post("/upload", upload.single('avatar'), function(req, res) {
console.log(req.file); // <- ALWAYS UNDEFINED
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query('INSERT INTO avatars (image) VALUES(?)', req.file,
function (error, results, fields) {
if(error){
console.log("Error: " + error);
res.status(400).send(error);
}
res.status(200).end(JSON.stringify(results));
connection.release();
if (error) throw error;
});
});
});
html:
<form enctype="multipart/form-data">
<input class="form-control"
(change)="onFileSelected($event)"
type="file" name="avatar">
<button type="submit" class="btn btn-danger float-right" (click)="onUpload()">Upload image</button>
</form>
ctrl:
onFileSelected(event) {
if(event.target.files.length > 0) {
this.uploadImage = <File>event.target.files[0];
}
}
onUpload() {
if(this.uploadImage) {
this.friendService.uploadFile(this.uploadImage)
.subscribe(
data => {
return true;
},
error => {
console.error('Error for image upload ' + error);
return false;
})
}
}
service:
uploadFile(file): Observable<any> {
return this.http.post(`${this.apiUrl}/upload`, file)
.map(res => res.json())
.catch(this.handleError);
}
db mysql avatars table:
Field - image
Type - blob
Null - NO
Key Default Extra - Empty
while uploading file it should be form data and content type should be multipart/form-data
For your reference: File Upload In Angular?.
I hope this will help you.
I am making a http request from my angular2+ code to database present in node.js file. The ajax call from angular2+ hits the controller.js file and then redirects to service.js file which has the connection to the database:
angular.ts ==> controller.js ==> service.js
From the database the service.js file gives the output to controller.js file and then answers the ajax call to angular.ts file:
service.js ==> controller.js ==> angular.ts
However, I am getting the error:
POST http://localhost:8096/dashboard/abcEntireSuccess1/ 404 (Not Found)
UPDATED
Cannot GET /dashboard/experianEntireSuccess1/
And one more issue -
UnauthorizedError: No authorization token was found
And one more issue -
After coming back from the hit in service.js which has the data i want ==> to => controller.js , here the data is acquired is undefined. As seen below -
The output on Nodejs -
output -
service.js
closed connection
yessss [ RowDataPacket { ....
controller.js
we are coming back to controller undefined
some error occured of abcEntireSuccess1
My Entire Code:
UPDATED
abc.component.ts
viewAbcEntireSuccess1() {
var url = config.url;
var port = config.port;
this.http.post("http://" + url + ":" + port + "/dashboard
/abcEntireSuccess1/", this.emptyObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(resultConnection => this.resultConnection =
resultConnection.json(), )
.subscribe((res: Response) => {
this.records = res;
this.resultConnectionlength = this.resultConnection.length;
});
}
abc.controller.js
router.post('/experianEntireSuccess1',experianEntireSuccess1);
module.exports = router;
function abcEntireSuccess1(req, res) {
dashboardService.abcEntireSuccess1(req.body)
.then(function (result) {
console.log("we are coming back to controller",result)
if (result.length > 0) {
console.log("we get data in node of abcEntireSuccess1 ::
" + Object.values(result));
console.log(result.length + " record found ");
res.send(result);
}
else {
result=[];
res.send(result);
}
})
.catch(function (err) {
res.status(400).send(err);
console.log("some error occured of abcEntireSuccess1");
});
}
abc.service.js
async function abcEntireSuccess1() {
console.log("function called")
const db = new Database();
await db.query(`select * from TRANSACTION_PAYLOAD where INTERFACE_NAME
= 'Abc' AND (STATUS ='SUCCESS_RESPONSE')`
).then(rows => {
console.log("closed connection");
console.log("yessss",rows)
return rows;
});
};
class Database {
constructor() {
this.connection = mysql.createConnection({
host: "127.0.0.1",
user: "abc",
password: "abc",
database: "DB"
});
}
query(sql, args) {
console.log("sql is", sql)
return new Promise((resolve, reject) => {
this.connection.query(sql, (err, rows) => {
console.log("connection function called")
if (err) {
console.log("error is", err)
return reject(err);
}
console.log("rows are",rows);
resolve(rows);
});
});
}
close() {
console.log("calling connection close")
return new Promise((resolve, reject) => {
console.log("called connection close")
this.connection.end(err => {
if (err){
return reject(err);
}
resolve();
});
});
}
}