Sequelize, Deleting multiple rows with React - javascript

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) => {

Related

params in url undefined - axios, react, express

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);
}
});
});

get route is correct but api is still not working(fetching nothing)

I am trying to make a get route for this API:
https://api.nasa.gov/mars-photos/api/v1/rovers/opportunity/photos?sol=1000&api_key=92Ll6nGuQhfGjZnT2gxaUgiBhlCJ9K1zi2Fv5ONn
And although the syntax for the get route, the API still doesn't work in postman nor in client-side.
Here's the get route code:
app.get('/roverInfo/:rover_name', async (req, res) => {
const { rover_name } = req.params
try {
let images = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/${rover_name}/photos?sol=1000&api_key=${process.env.API_KEY}`).then((res) => res.json())
res.send({ images })
} catch (err) {
console.log('error:', err)
}
})
sandbox here
and here's the client-side request:
const showRovers = async (rovers) => {
try {
await fetch(`https://localhost:3000/roverInfo/:rover_name`)
.then((res) => {
return res.json()
})
.then((rovers) => updateStore(store, { rovers }), console.log(rovers))
} catch (error) {
console.log('errors:', error)
}
}
and here's the error I am getting:
Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
ADVISE: Don't mix await/async with .then, use either one
app.get("/roverInfo/:rover_name", async (req, res) => {
const { rover_name } = req.params;
try {
const res = await fetch(
`https://api.nasa.gov/mars-photos/api/v1/rovers/${rover_name}/photos?sol=1000&api_key=${process.env.API_KEY}`
) // removed .then
const images = await res.json(); // await response to json
res.send({ images });
} catch (err) {
console.log("error:", err);
}
});
02. should be http instead of https
03. need to pass rover name to param instead of using :rover_name
let getRovers = showRovers('opportunity');
const showRovers = async (roverName) => {
try {
console.log("roverName", roverName)
// use http here
await fetch(`http://localhost:3000/roverInfo/${roverName}`)
.then((res) => {
return res.json();
})
.then((rovers) => updateStore(store, { rovers }));
} catch (error) {
console.log("errors:", error);
}
};

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);
})

Firebase Querying?

I have an issue querying in my firebase database. I am trying to get all data of an authenticated user from my endpoint ".../api/user".
This is the route in my code:
// GET DATA OF USER
router.route("/user").get(FBAuth, getAuthenticatedUser);
Here I use a middleware which decodes the token and sets it in the req.user, and of course verifies if the user is authenticated:
// FBAuth middleware
module.exports = (req, res, next) => {
admin
.auth()
.verifyIdToken(idToken)
.then((decodedToken) => {
req.user = decodedToken;
return db
.collectionGroup("users")
.where("idUser", "==", req.user.uid)
.limit(1)
.get();
})
.then((data) => {
req.user.name = data.docs[0].data().name
return next();
})
.catch((err) => {
console.error("Error while verifying token", err);
return res.status(403).json(err);
});
};
All the above works fine, but after the req.user set successfully, we go to the function "getAuthenticatedUser" which doesn't work:
//Controller
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup("users")
.where("email", "==", req.user.email) //".where("idUser", "==", req.user.uid)" nothing works here
.limit(1)
.get()
.then((doc) => {
if (doc.exists) { // Always goes to the else no matter what query I do
userData.credentials = doc.data();
return db
.collection("comptes")
.doc(req.user.name)
.collection("courses")
.get();
}else{
return res.status(400).json({email: 'Email not found => ' + req.user.email});
// the req.user.email does exist and contain the right email, and also exists in the database...
}
})
.then((data) => {
if (data.exists) {
userData.courses= [];
data.forEach((doc) => {
userData.courses.push(doc.data());
});
}
return res.json(userData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
I don't see how the query can work for the logging, for the middleware but not for the actual controller which must use this setup before cause it is a private route?
I finally fixed it, if anyone has the same issue here is the solution:
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup("users")
.where("email", "==", req.user.email)
.limit(1)
.get()
.then((doc) => {
if (doc.docs[0].exists) { // <----- doc.docs contain a list of data
userData.credentials = doc.docs[0].data();
return db
.collection("comptes")
.doc(req.user.name)
.collection("courses")
.get();
}
})
.then((data) => {
if (data.exists) {
userData.courses= [];
data.forEach((doc) => {
userData.courses.push(doc.data());
});
}
return res.json(userData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};

Axios not receive response and error of the server Node

i'm trying do a request POST using axios.js but the axios not is working, it not give the response or error, the console.log stay empty when i do the request, i dont know why. someone know?
My request axios.js:
handleLogin = () => {
this.setState({
loading: true
})
axios.post("/login", {
body: JSON.stringify({
...this.state
})
})
.then(response =>
localStorage.setItem('user-token', response.token),
this.setState({
loading: false
})
)
.catch(error =>
console.log(error),
this.setState({
loading: false
})
)
};
My middleware(isManager):
const {
findByMail
} = require('../data/acl/acl.model');
module.exports =
async function isAuthenticated(req, res, next) {
const acl = await findByMail(req.body.username);
if (acl && acl.role === "MANAGER") {
next()
} else {
return res.status(401).send({
message: "ERROR: YOU DONT HAVE ACCESS"
})
}
}
My route that axios use:
const isbmer = passport.authenticate('ldapauth', {
session: false
});
router.post('/', [isManager, isbmer], (req, res) => {
let id = req.user.ibmSerialNumber;
const email = req.user.preferredIdentity;
const name = req.user.cn;
const json = {
id,
email,
name
};
const expiresIn = process.env.NODE_ENV === 'local' ? '365d' : '10h';
const token = jwt.sign(json, process.env.JWT_SECRET, {
expiresIn
});
res.status(200).send({
auth: true,
token
});
});
Someone help me?When i do the request, nothing work..

Categories

Resources