I'm trying to sign in but getting 400 Bad Request & "Wrong credentialsss".
app.post("/signin", (req, res) => {
const {email, password} = req.body;
db.from ('login').select('*').eq("email", email)
.then(data => {
const isValid = bcrypt.compareSync(password, data[0].hash)
if (isValid) {
return db.from ('users').select('*')
.eq ("email", email)
.then(resp => res.json(resp[0]))
.catch(err => res.status(400).json("failed to get user"))
} else {
res.status(400).json("wrong credentials")
}
})
.catch(err=>res.status(400).json("wrong credentialsss")) // <-- HERE
})
However, when I update the code as below, I can successfully fetch the data. I guess the problem is the middle part but have no idea.
app.post("/signin", (req, res) => {
const {email, password} = req.body;
db.from ('login').select('*').eq("email", email)
.then(data => res.json(data))
.catch(err=>res.status(400).json("wrong credentialsss"))
})
EDIT: This is what I get from second code
{
"error": null,
"data": [
{
"id": 1,
"hash": "$2a$10$JJ/i0c1bcu/1ZcV8f8DSGOipZUm5FLTGmvEygPjdpny3k0DI9/jrC",
"email": "admin#gmail.com"
}
],
"count": null,
"status": 200,
"statusText": "OK"
Tried to log the error
"message": "Cannot read properties of undefined (reading 'hash')",
"error": {}
Try replacing "data[0].hash" with "data.data[0].hash"
You receive a "data" object in the .then and then need to access the "data" property that contains the array of objects
.then(data => {
const isValid = bcrypt.compareSync(password, data.data[0].hash)
if (isValid) {
return db.from ('users').select('*')
.eq ("email", email)
.then(resp => res.json(resp[0]))
.catch(err => res.status(400).json("failed to get user"))
} else {
res.status(400).json("wrong credentials")
}
})
Sorry, I wanted to comment, but my reputation prevents me. Hence asking this question here. Instead of printing data[0].hash, did you try printing data[0] or data, just to ensure you are getting it in the right format and need no conversions.
Related
I need assistance in fetching data back to client as soon as it is posted to the database without reloading the page. The structure I have at present only shows the posts on page reload. Below are my codes.
const [pst, setPst] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
const v2 = PST_REGEX.test(pst);
if (!v2) {
// setErrMsg("Invalid Entry");
return;
}
try {
const response = await axios
.post(DASHBOARD_URL, JSON.stringify({ pst }), {
headers: { "Content-Type": "application/json" },
withCredentials: true,
})
} catch (err) {
console.log(err)
}
};
Post Controller
const handleNewPost = async (req, res) => {
const { pst } = req.body;
if (!pst) return res.status(400).json({ message: "Field cannot be blank" });
try {
//create and store the new post
const result = await Userpost.create({
post: pst,
});
console.log(result);
res.status(201).json({ success: `New post ${pst} created!` });
} catch (err) {
res.status(500).json({ message: err.message });
}
};
There are some ways from which you can achieve your solution.
Method 1:
You can return newly created data from backend as success response. Lets assume you got response as follow:
{
"message": "Data created Successfully",
"status" : "201",
"data": [{
"id": "1234",
"title": "Blog title",
"description" : "Blog description"
}]
}
Then you can simply add response to you previous state as:
setPst([...pst, ...message.data]) // message.data is response from your endpoint
Method 2:
You can use socket io for real time experience: https://socket.io/
I am using axios for the request of my own api, everything works correctly except the DELETE request, I looked for information about the error but I have not found the solution. when I send the request to the server I get this error: "xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden)".
I put this line of code in Package.Json to avoid problems with CORS:
"proxy": "http://localhost:8080/api"
This would be my api, for the operation I pass the post id by url and the user id:
(I tried it in postman and it works without any problem)
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.userId === req.body.userId) {
await post.deleteOne();
res.status(200).json("the post has been deleted");
} else {
res.status(403).json("you can delete only your post");
}
} catch (err) {
res.status(500).json(err);
}
});
and this is where I consume my api:
const Post = ({ date, _id,userId, description }) => {
const handleDelete = async () => {
try {
await axios.delete('posts/' + _id, { userId: currentUser._id })
} catch (error) {
console.log(error)
}
}
return(
<div onClick={handleDelete }>
//component content
</div>
)
}
export default Post
I solved it, sending a data object to my api (inside that object I put the user id):
const handleDelete = async () => {
try {
await axios.delete('/posts/' + _id, {
data: {
userId: currentUser._id
}
}
)
} catch (error) {
console.log(error)
}
}
When i get the string from my discord bot, i make a post request to my api
axios.post(`http://localhost:8080/api/post/ban/${discord_id}`, {}, {
headers: {
key: key
}
}).then((response) => {
console.log(response.data)
})
But when its submitted the event isnt activated
When i sent string the length of 17 or less or length of 19 or more it worked but not when string length is 18
app.post('/api/post/ban/:discord_id/', async function (req, res) {
let id = req.params.discord_id
let header = req.headers;
if(isNaN(id)) return res.send({
"error": {
"message": "USER_ID_MUST_BE_NUMBER",
"code": "400"
}
});
if(id.length < 19 || id.length > 19) return res.send({
"error": {
"message": "ID_IS_NOT_VALID",
"code": "400"
}
});
if(header.key != key) return res.send({
"error": {
"message": "OWNER_ONLY",
"code": "none"
}
});
await banModel.findByIdAndUpdate(banID, {
$addToSet: { "bannedUsers": `${id}`}
});
return res.send({
"success": {
"message": "ADDED_USER_TO_BANS",
"code": "201"
}
});
});`
i fixed it heres the answer:
axios.post(`http://localhost:8080/api/post/ban/${discord_id}/`,{},{
headers: {
key: key
}
})
.then(function (response) {
console.log(response.data)
if(response.data.error) {
switch(response.data.error.code) {
case "404":
return interaction.reply("Channel not found!");
case "422":
return interaction.reply("Invalid parameters!");
case "400":
return interaction.reply("Invalid types of objects!");
case "409":
return interaction.reply("U already exist on our Database!");
case "none":
switch(response.data.error.message) {
case "INVALID_VIDEO_URL":
return interaction.reply("Invalid video url")
case "OWNER_ONLY":
return interaction.reply("Owner only API")
}
break;
}
}
if(response.data.success) return interaction.reply("Succesfully added your video!")
})
.catch(function (error) {
console.log(error);
});
I am building an ecommerce with mern stack
When I make request from react to node and it fails it show the status code with error on the page.
is there a way to prevent this from happening
enter image description here
React code
export const createCategories = async(name, token) => {
return await axios.post(
`${process.env.REACT_APP_SERVER_APP_URL}/api/category`,
name,
{
headers: {
'x-header-token' : token
}
}
)
}
const handleSubmit = async(e) => {
e.preventDefault();
setLoading(true)
try{
createCategories(category, localStorage.getItem('token'))
.then(res => {
console.log(res)
setLoading(false)
setCompleted(true)
setCreateCategory(res.data)
});
}catch(err){
setError(true)
setErrorMsg({
"msg": err.response.data
})
}
}
nodejs code
try{
const {name} = req.body;
const category = await new Category({ name, slug: slugify(name)}).save();
res.json({'msg': "Category Created"})
}catch(err){
res.status(400).send("Create Category Failed...")
console.log(err)
}
you should use catch block
createCategories(name,token).then(res => {
// if success in response
}).catch(error => {
// if error in response
})
I am working to validate data input from an API call using express-validator version 6.11.1 and every time I validate using either check or body, I get the error below:
TypeError: body(...).not(...).IsEmpty is not a function
I created a helper called validator.js with the code below
const { body, validationResult } = require('express-validator')
const bcrypt = require('bcrypt')
const signupValidation = () => {
return [
body('firstname')
.not().IsEmpty().withMessage('Firstname field is required'),
body('lastname')
.not().IsEmpty().withMessage('Lastname field is required')
]
}
const validate = (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next()
}
const extractedErrors = []
errors.array().map(err => extractedErrors.push({ msg: err.msg }))
res.status(200).json({
statusCode: 422,
error: extractedErrors
})
}
module.exports = {
signupValidation,
validate
}
The route where I am calling it looks like
const { signupValidation, validate } = require('../../helpers/validator')
//Endpoint to create new merchant
router.post('/account/create-merchant', signupValidation(), validate, async (req, res) => {
res.status(200).json({
statusCode: 201,
message: req.body
})
})
Sample Data from the API
{
"firstname": "",
"lastname": "Jon",
"phone" : "*****",
"email" : "oayayayaya",
"password": "******"
}
Can you please guide me on what to do to solve the error message (TypeError: body(...).not(...).IsEmpty is not a function)
I think it should be isEmpty() instead of IsEmpty(), try this:
const signupValidation = () => {
return [
body('firstname')
.not().isEmpty().withMessage('Firstname field is required'),
body('lastname')
.not().isEmpty().withMessage('Lastname field is required')
]
}
Check the doc here