Internal server error 500 react post to firebase - reactjs

I'm getting a 500 error when posting to my firebase database. However, when I post via postman, it works fine, thus I'm having a lot of trouble debugging this. For the moment, I've hardcoded the categoryId and also the newRow, to make sure there wasn't a problem with my state somehow.
I think the handleSubmit is the only relevant function
handleSubmit = (event) => {
event.preventDefault();
const categoryId = "1RegisterInfo";
const newRow = {
index: "3",
body: "this.state.body",
dataType: "this.state.dataType",
visit: "test",
};
this.props.postRow(categoryId, { newRow });
};
action
export const postRow = (categoryId, rowData) => (dispatch) => {
dispatch({ type: "LOADING_UI" });
axios
.post(`/category/${categoryId}`, rowData)
.then((res) => {
dispatch({
type: "POST_ROW",
payload: res.data,
});
dispatch(clearErrors());
})
.catch((err) => {
dispatch({
type: "SET_ERRORS",
payload: err.response.data,
});
});
};
cloud function
exports.postRow = (req, res) => {
if (req.body.body.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.index.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.dataType.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
if (req.body.visit.trim() === "") {
return res.status(400).json({ comment: "Must not be empty" });
}
const newRow = {
index: req.body.index,
dataType: req.body.dataType,
visit: req.body.visit,
body: req.body.body,
createdAt: new Date().toISOString(),
categoryId: req.params.categoryId,
disapproveCount: 0,
approveCount: 0,
};
db.doc(`/categories/${req.params.categoryId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: "Category not found" });
}
})
.then(() => {
return db.collection("rows").add(newRow);
})
.then(() => {
res.json(newRow);
})
.catch((err) => {
console.log(err);
res.status(500).json({ error: "Something went wrong" });
});
};
Any help appreciated!

You're not sending the right payload.
{ newRow }
is the same as
{
newRow: {
index: '3',
body: this.state.body,
dataType: this.state.dataType,
visit: 'test',
},
}
You're passing the above data in the request body and so req.body.body is undefined causing req.body.body.trim() to fail.
this.props.postRow(categoryId, { newRow })
should be
this.props.postRow(categoryId, newRow)
I would recommend using Joi or something similar to validate the request payload before trying to do any other operation.

Related

I am trying to make a payment using Braintree but It shows "Cannot determine payment method"

Hare is the erros message in console. "Cannot determine payment method".
{errors: {…}, params: {…}, message: 'Cannot determine payment
method.', success: false} errors: {validationErrors: {…},
errorCollections: {…}} message: "Cannot determine payment method."
params: {transaction: {…}} success: false [[Prototype]]: Object
Let me tell one thing I have made token properly. Hare I attached few segment of my code.
const buy = () => {
setData({ loading: true });
let nonce;
let getNonce = data.instance
.requestPaymentMethod()
.then(data => {
nonce = data.nonce;
const paymentData = {
paymentMethodNonce: nonce,
amount: getTotal(products)
};
processPayment(userId, token, paymentData)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
})
.catch(error => {
setData({ ...data, error: error.message });
});
};
Hare is the process payment Controller
exports.processPayment = (req, res) => {
const nonceFromTheClient = req.body.payment_method_nonce;
const amountFromTheClient = req.body.amount;
// charge
const newTransaction = gateway.transaction.sale(
{
amount: amountFromTheClient,
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
},
(err, result) => {
if (err) {
res.status(500).json(err);
} else {
res.json(result);
}
}
);
};

Returning response from Dispatch

I'm implementing login functionality to my application and am trying to return the response from a dispatched thunk action. I'm purposely entering the incorrect password because i'd like for the errors that are set in my backend to display within an antd notification on the frontend. My expected response should be:
return res.status(400).json({
success: false,
message: 'Invalid email address or password.',
});
but instead i'm getting the following in the console:
Error: Request failed with status code 400
Route:
const loginUser = async (req, res) => {
// Validate Login Input
const { error } = validateLoginInput(req.body);
if (error)
return res
.status(400)
.json({ success: false, message: error.details[0].message });
req.body.email = req.body.email.toLowerCase();
req.body = sanitize(req.body);
const { email, password } = req.body;
try {
// See if user exists
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({
success: false,
message: 'Invalid email address or password.',
});
}
// Compare passwords
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({
success: false,
message: 'Invalid email address or password.',
});
}
// Return jsonwebtoken
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: 3600 },
(error, token) => {
if (error) throw error;
res.json({ token });
}
);
} catch (error) {
res.status(500).json({ success: false, messsage: 'Server error' });
}
};
Actions:
export const loginBegin = () => ({
type: LOGIN_BEGIN,
});
export const loginSuccess = (user) => ({
type: LOGIN_SUCCESS,
payload: user,
});
export const loginFail = (error) => ({
type: LOGIN_FAIL,
payload: error,
});
Thunk:
export const attemptLogin = (formData) => async (dispatch) => {
dispatch(loginBegin());
return await postLogin(formData)
.then((res) => {
dispatch(loginSuccess(res.data));
console.log(res.data); <-- This doesn't even show in console
})
// .then(() => {
// setTimeout(() => {
// dispatch(push('/app'));
// }, 2000);
// })
.catch((error) => {
dispatch(loginFail(error));
});
};
onSubmit:
const onSubmit = async (values) => {
const { email, password } = values;
setLoading(true);
try {
const response = await dispatch(attemptLogin({ email, password }));
console.log(response); <-- returns undefined
if (response.data.success) {
setLoading(false);
notification['success']({
message: 'Congrats!',
description: response.message,
});
} else {
notification['error']({
message: 'Uh-oh!',
description: response.message,
});
}
} catch (error) {
console.log(error);
}
};
The problem is that you are not returning the response in the promise. Also, if you are getting a 400 response, it probably rejects the promise or throws an error.
export const attemptLogin = (formData) => async (dispatch) => {
dispatch(loginBegin());
return await postLogin(formData)
.then((res) => {
dispatch(loginSuccess(res.data));
return res;
})
.catch((error) => {
dispatch(loginFail(error));
return error; // this will only work if the error is the response object.
});
};

I have data on the front end but it's undefined in the back end

Hello guys i have a problem with my data on the fetch indeed on the front side i do this to fetch my data:
() => {
const data = {clubChoix: element.nomClub};
const options = {
method: 'POST',
body: data,
};
fetch('http://localhost:8080/inscription/choixclub', options)
.then((response) => {
return response.json();
})
.then(
(responseData) => {
console.log(responseData);
},
(err) => {
console.log(err);
},
);
})
And the i put a console.log to make sure that what i send is real
(console.log(element.nomClub),
The result of this one is:
LOG: Nimes Olympique
In my thought the "const data = {choixClub: element.nomClub};" in the data is like a req.body.clubChoix but in the back end so why when i console log it the req.body it's undefined ?
in case you want to see my back end there it is:
choixClub: (req, res) => {
User.updateOne(
{ _id: "5f47a46e36588f5e2a1e4f35" },
{
$set: {
club: req.body.clubChoix,
},
},
(err) => {
if (err) {
console.log(err);
res.json({ message: "une erreur s'est produite" });
} else {
console.log(req.body.clubChoix);
res.json({ message: "Votre club a bien été enregistré" });
}
}
);
},

adding data in firebase firestore React

I have singUp function. I successfuly create a new user in Authentication section. After that I can even get his uid. But I have no idea why setting a new document in collection user function doesn't work. Like it would be never start.. Even .then() or .catch() methods doesn't show their console.log(). I am using almost the same code in another project and everything is fine there.
export const signUp = (newUser) => {
return (dispatch, getState) => {
firebase.firestore().collection('users').where('nick', '==', newUser.nick).get()
.then(snapshot => {
if (snapshot.empty) {
firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
).then((resp) => {
console.log(resp)
console.log(resp.user.uid)
firebase.firestore().collection("users").doc(resp.user.uid).set({
name: newUser.name,
age: newUser.age
}).then(function () {
console.log("Document successfully written!");
}).catch(function (error) {
console.error("Error writing document: ", error);
});
}).then(() => {
dispatch({ type: "SIGNUP_SUCCESS" });
}).catch((err) => {
console.log(err)
let error;
if (err.code === 'auth/email-already-in-use')
error = 'Adres e-mail jest już w użyciu!'
dispatch({ type: "SIGNUP_ERROR", error })
})
} else {
let error = 'Ten nick jest już zajęty!'
dispatch({ type: "SIGNUP_ERROR", error })
}
})
}
}
And my console :
You need to return the promise from setting the user's collection as follows:
export const signUp = (newUser) => {
return (dispatch, getState) => {
firebase.firestore().collection('users').where('nick', '==', newUser.nick).get()
.then(snapshot => {
if (snapshot.empty) {
firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
).then((resp) => {
console.log(resp)
console.log(resp.user.uid)
// ******* add the return statement here *******
return firebase.firestore().collection("users").doc(resp.user.uid).set({
name: newUser.name,
age: newUser.age
}).then(function () {
console.log("Document successfully written!");
}).catch(function (error) {
console.error("Error writing document: ", error);
});
}).then(() => {
dispatch({ type: "SIGNUP_SUCCESS" });
}).catch((err) => {
console.log(err)
let error;
if (err.code === 'auth/email-already-in-use')
error = 'Adres e-mail jest już w użyciu!'
dispatch({ type: "SIGNUP_ERROR", error })
})
} else {
let error = 'Ten nick jest już zajęty!'
dispatch({ type: "SIGNUP_ERROR", error })
}
})
}
}

Axios > Express.router – Update(.put) method returning 404

I am trying to finish building the last CRUD method of my App. (C, R and D) all done. But updating seems to be proving bothersome. I have a function which combines the object ID with the new content to update with. I am getting Error: Request failed with status code 404printed to the console.
I think I'm failing to reach the database item using the ID.
Function which gathers the data and initiates the request
handleClick(e) {
e.preventDefault()
const data = {
id: this.props.sid, //someuniqueid
body: {
name: this.state.name, //foo
details: this.state.details, //bar
content: this.state.content, //baz
},
}
api
.updateSnippet(data)
.then(result => {
this.setState({
name: '',
details: '',
content: '',
message: `'${this.state.name}' has been created`,
})
setTimeout(() => {
this.setState({
message: null,
})
}, 2000)
console.log('UPDATE DATA SUCCESS!')
})
.catch(err => this.setState({ message: err.toString() }))
}
api.js - uses axios to fire the request (this may be where I am failing).
import axios from 'axios'
const service = axios.create({
baseURL:
process.env.NODE_ENV === 'production'
? '/api'
: 'http://localhost:5000/api',
withCredentials: true,
})
const errHandler = err => {
console.error(err)
if (err.response && err.response.data) {
console.error('API response', err.response.data)
throw err.response.data.message
}
throw err
}
export default {
service: service,
updateSnippet(data) {
console.log(data.id) //someuniqueid
console.log(data.body) //{name: "foo", details: "bar", content: "baz"}
return service
.put('/snippets' + data.id, {
data: data.body,
})
.then(res => res.data)
.catch(errHandler)
},
}
Snippet.js (schema)
const mongoose = require('mongoose')
const snippetSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'The snippet name is required'],
minlength: 1,
},
details: {
type: [String],
default: [],
},
content: {
type: String,
},
})
const Snippet = mongoose.model('Snippet', snippetSchema)
module.exports = Snippet
Relevant route in "routes/snippets.js" - This could also be where I am falling over
router.put('/', function(req, res) {
console.log(req.body)
Snippet.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content,
},
{ new: true },
function(err, response) {
if (err) {
console.log('we hit an error' + err)
res.json({
message: 'Database Update Failure',
})
}
console.log('This is the Response: ' + response)
}
)
})
You are sending the id in the url, so you need to parse it from req.params.id.
I also returned response.
routes/snippets.js
router.put("/:id", function(req, res) {
console.log(req.body);
Snippet.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content
},
{ new: true },
function(err, response) {
if (err) {
console.log("we hit an error" + err);
return res.json({
message: "Database Update Failure"
});
}
return res.send(response);
}
);
});
Also you need to update this line in api.js. Just add / after snippets
.put('/snippets' + data.id, { =>
.put('/snippets/' + data.id, {

Resources