params in url undefined - axios, react, express - javascript

I'm trying to delete some data from a mysql database with the code:
app.delete("/api/deleteHomework/:homeworkName", (req, res) => {
const homeworkName = req.params.homeworkName
connection.query(
"DELETE FROM homework WHERE name = ?",
[homeworkName],
(err, result) => {
if(result){
res.send({ message: result })
console.log(result)
}
if(err){
console.log(err)
}
}
)
})
and then the homeworkName is passed from the front end with the code:
const deleteHw = (homework) => {
Axios.delete(`http://localhost:1337/api/deleteHomework/${homework}`)
.then((response) => {
if(response){
console.log(response)
} else{
console.log("error")
}
})
}
<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => {deleteHw(value.homeworkName)}} />
However it says the params in the url is undefined:
url: "http://localhost:1337/api/deleteHomework/undefined"

Pass the props "value" directly in the delete function
export default function YourComponent({ value }) {
...
const deleteHw = () => {
Axios.delete(`http://localhost:1337/api/deleteHomework/${value.homeworkName}`) // here
.then((response) => {
if(response){
console.log(response)
} else{
console.log("error")
}
})
}
<DeleteForeverIcon className={classes.deleteHwIcon} onClick={deleteHw} />
Back side
app.delete('/api/deleteHomework/:homeworkName', (req, res) => {
connection.query(`DELETE FROM homework WHERE name=${req.params.homeworkName}`, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});

Related

getting req.params is showing undefined

I need product id that's _id from my mongo document but when I consoled req.params.id it is showing undefined to my /shop page and I'm following mvc format
// get request://
router.get("/shop/:id",userController.shopPage)
//route://
getProductPage: (req, res) => {
try{
let proId = req.params.id;
console.log(proId)
productHelpers
.getProduct(proId)
.then((products) => {
res.render("user/view-product",{products}); })}
catch(error){
}
//get Product//
getProduct: (proId) => {
console.log(proId)
return new Promise((resolve, reject) => {
try {
db.products.find({_id:proId}).then((products) => {
resolve(products);
});
} catch (error) {
console.log(error);
}
});
},

Page not refreshing after res.redirect(303, '/') done after DELETE request

I've managed to redirect a page after a DELETE request to the home GET route, but the page isn't actually refreshing (i.e. the deleted item still appears) and it isn't until I manually refresh the page that it is removed. I've done some console.logs and the item has definitely been deleted by the time it has redirected to .get('/'). Any ideas why this isn't working?
app.js - routes only
app.route('/')
.get((req, res) => {
connection.query('SELECT * FROM todos', (err, results) => {
if (err) throw err;
console.log(results);
console.log('Todos read from database');
res.render('home', { results: results });
});
})
.post((req, res) => {
const todoItem = req.body.todo;
connection.query('INSERT INTO todos (todo) VALUES (?)', todoItem, err => {
if (err) throw err;
console.log('Todo inserted into database.');
res.redirect('/');
});
})
.delete((req, res) => {
const todo = req.body.todoItem;
connection.query('DELETE FROM todos WHERE todo=?', todo, err => {
if (err) throw err;
console.log('Todo deleted from database.');
});
res.redirect(303, '/');
});
client.js
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click', handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clickeTodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/', {
method: 'DELETE',
body: JSON.stringify(clickeTodo),
headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => response.json())
.catch(err => console.log(err));
}
Terminal output
Todo deleted from database.
[ RowDataPacket { todo: 'Clean' }, RowDataPacket { todo: 'Read' } ]
Todos read from database
I've learned that fetch won't send the browser to a new page if it gets a redirect response and this needs to be done on the client side instead. I've added window.location = response.url and it now works:
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click', handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clickeTodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/', {
method: 'DELETE',
body: JSON.stringify(clickeTodo),
headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => {
window.location = response.url;
response.json();
})
.catch(err => console.log(err));
}

Request Aborted on axios.get reactJS

I'm trying to make get request via token from local storage but it is giving me Request aborted error.
Here is My nodeJS code :
//Read
app.get('/:username',verify, (req, res) => {
console.log('Welcome to roffys server')
Todo.find({'username' : req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
res.json(todo)
}
})
})
Here is the Verify function :
const jwt = require('jsonwebtoken')
module.exports = function (req,res,next){
const token = req.header('Authentication')
if(!token) return res.status(401).send('Access Denied')
try {
const verified = jwt.verify(token, 'secretkey')
req.user = verified
}catch (err) {
res.status(400).send(
'Invalid token'
)
next()
}
And here is my FE on ReactJS component:
componentDidMount() {
axios
.get(`http://localhost:8080/${localStorage.getItem('username')}`,{
headers : {
Authentication : localStorage.getItem('token')
}
})
.then((res) => {
this.setState({todos: res.data})
this.setPageCount()
})
.catch((err) => {
console.log("err", err);
});
}
None of yow methods return anything.
componentDidMout () {
return axios.get(url, config)
.then (res=> this.setState(myProp: res.data});
......
Back
var verify = require(“./path/to verify”);
//Read
app.get('/:username',verify, (req, res) => {
return Todo.find({'username' : req.params.username})
.exec()
.then(todo=> res.json(todo))
.catch(console.log);
})

I want to get employee's department data from the req department id passed to the url

How do I use optional query filter on these route like "/employees?department=4" and returning data where department number is 4
app.get("/employees", (req, res) => {
dataService.getAllEmployees().then(function(data) {
res.json(data);
}).catch(function(err) {
var error = { "message": err };
res.json(error);
});
I already have function in dataService module that return a promise of department with id below
function getEmployeesByDepartment(department) {
return new Promise((resolve, reject) => {
try {
employees.forEach((element) => {
if (element.department == department) {
resolve(element);
}
});
} catch (error) {
reject("no data returned");
}
});
}
You can use req.query to fetch query string data and pass department to getEmployeesByDepartment function.
app.get("/employees", (req, res) => {
var department = req.query.department || "";
if(department){
getEmployeesByDepartment(department).then(data => res.json(data));
}
else{
dataService.getAllEmployees().then((data) => {
res.json(data);
}).catch((err) => {
var error = { "message": err };
res.json(error);
}
);
You can access the query parameters using the req.query object.
In your case the code will be something like:
if (req.query.department) {
return getEmployeesByDepartment(req.query.department).then(
data => res.json(data)
);
} else {
return dataService.getAllEmployees().then(
data => res.json(data)
);
}

Sequelize, Deleting multiple rows with React

I'm using React with a Postgres DB with Sequelize.
within my project, I have a promise that is "suppose" to delete all songs relating to the album, using the the Album.id in my state.
** Instead of deleting the rows of songs relating to the Album, after the delete request in the database, it removes the value of the AlbumId of the song. **
Is there an update I am missing
When I console.log outside of the service and in the promise this.state.Album.id remains the same.
It hit's the server with the appropriate number.
This is the function within the React Component
DeleteAlbum (e) {
e.preventDefault()
axios.delete(`${domain}/albums/${this.state.Album.id}`)
.then((res) => {
axios.delete(`${domain}/songs/ByAlbumId/${this.state.Album.id}`)
.then((res) => {
window.location.href = '/#/'
})
.catch((error) => {
console.log('axios error', error)
})
})
.catch((error) => {
console.log('axios error', error)
})
}
This is the Database to the Songs Route
const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
const db = require('./../models')
const Song = db.Song
router.use(bodyParser.json({ extended: false }))
const exists = (req) => {
if (typeof parseInt(req.params.id) === 'number') {
Album.findOne({
where: {
id: req.params.id
}
})
.then((album) => {
if (album) {
return true
};
return false
})
.catch((err) => {
return false
})
} else {
return false
}
}
router.delete('/ByAlbumId/:id', function (req, res) {
Song.destroy({
where: {
AlbumId: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
})
router.delete('/:id', function (req, res) {
if (exists) {
Song.destroy({
where: {
id: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
} else {
res.json({success: false})
}
})
This is the Album Route
const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
const db = require('./../models')
const Album = db.Album
router.use(bodyParser.json({ extended: false }))
const exists = (req) => {
if (typeof parseInt(req.params.id) === 'number') {
Album.findOne({
where: {
id: req.params.id
}
})
.then((album) => {
if (album) {
return true
};
return false
})
.catch((err) => {
return false
})
} else {
return false
}
}
router.delete('/:id', function (req, res) {
if (exists) {
Album.destroy({
where: {
id: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
} else {
res.json({success: false})
}
})
If I place console logs all over the place, the output is what I expect it to be. There's is just something going wrong with Deleting two songs from my app. I can delete multiple songs if I hit the server directly with postman
Any idea?
You are actually destroying the album, before you destroy the songs.
In this case, since they probably have onDelete: 'SET NULL' option added, you will just de-associate the songs with that album.
Your fix will be to just replace the order of your calls :
// First we delete the songs and then the album
axios.delete(`${domain}/songs/ByAlbumId/${this.state.Album.id}`)
.then((res) => {
axios.delete(`${domain}/albums/${this.state.Album.id}`)
.then((res) => {

Categories

Resources