I am trying through the api to node
delete a record from the table likes
. I send the arguments to the url with axios
like: axios.delete(/likes, objeto, headers)
as with the method of creating likes but deleteLike
it does not take me back. However, front returns me a 403
since the middleware does not take the token. I don't know why createLike in back takes me and calls the function but not delete.
Front:
// React
import React, { useState } from 'react';
// Mui like icons
import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder';
import FavoriteIcon from '@mui/icons-material/Favorite';
// Axios
import axios from 'axios';
// React-cookies
import cookies from "js-cookie";
const LikeButton = (props) => {
const { post } = props;
const [isLiked, setIsLiked] = useState(false);
const [numberOfLikes, setNumberOfLikes] = useState(post.total_likes);
const createLike = async(post) => {
const headers = {
'content-type': 'application/json',
'auth-token': cookies.get('auth-token')
};
const like = {
post_id: post.id
}
let numLikes = parseInt(post.total_likes);
numLikes += 1;
console.log(numLikes)
try {
await axios.post('/likes', like, {headers: headers});
setIsLiked(true);
setNumberOfLikes(numLikes);
} catch (err) {
console.error(err);
}
}
const deleteLike = async(post) => {
console.log('deleting ...')
const headers = {
'content-type': 'application/json',
'auth-token': cookies.get('auth-token')
}
const like = {
post_id: post.id,
email: post.created_by
}
let numLikes = parseInt(post.total_likes);
numLikes -= 1;
try {
await axios.delete('/likes', like, {headers: headers});
setIsLiked(false);
setNumberOfLikes(numLikes);
} catch (err) {
console.error(err);
}
}
return(
(post.total_likes > 0 || isLiked) ?
<>
<FavoriteIcon
sx={{marginLeft: '10px', fill: 'red', cursor: 'pointer'}}
onClick={() => deleteLike(post)}
/>
<p>{numberOfLikes}</p>
</>
:
<FavoriteBorderIcon
sx={{marginLeft: '10px', fill: 'red', cursor: 'pointer'}}
onClick={() => createLike(post)}
/>
)
}
export default LikeButton;
Back:
const pool = require('../db');
const jwt = require('jsonwebtoken');
const createLike = async(req, res, next) => {
const { post_id } = req.body;
console.log('creating like ----------------------------------- >')
const token = req.headers['auth-token'];
if(!token) return res.status(403).send('Access Denied');
const decodedToken = jwt.verify(token, process.env.TOKEN_SECRET);
const userId = decodedToken && decodedToken.uid;
// try {
// const like = await pool.query('insert into likes (user_id, post_id) values ($1, $2)', [userId, post_id]);
// return res.json(like.rows[0]);
// } catch (err) {
// next(err);
// }
}
const deleteLike = async(req, res, next) => {
console.log('-----------------------> DELETE CALLED')
const { post_id, email } = req.body;
console.log('post_id', post_id);
console.log('email', email);
console.log('req', req.headers);
const userId = await pool.query('select * from users where email = $1', [email])
const postId = post_id;
// try {
// await pool.query('delete from likes where user_id=$1 and post_id = $2', [userId.rows[0].id, postId]);
// } catch (error) {
// res.json({message: 'Like not found'});
// }
}
module.exports = {
createLike,
deleteLike
}
Routes for likes:
const { Router } = require('express');
const router = Router();
const {
createLike,
deleteLike
} = require('../controllers/like.controller');
const { verifyTokenAuthorization } = require('../middleware/auth');
router.post('/likes', verifyTokenAuthorization, createLike);
router.delete('/likes', verifyTokenAuthorization, deleteLike);
module.exports = router;
According to the axios documentation , the method
delete
receives only two parameters: theurl
and optionally the configuration (config
):But in your code you are calling it with 3 parameters, that is why it does not work for you. Note that your third parameter is the headers, which of course never arrive.
In order to fix your problem, please refactor the code to: