In my React app, I am trying to access the error returned from this bit of server code.
User.findByUsername(req.body.username)
.then((foundUsername) => {
if (foundUsername) {
return res.status(422)
.json({
error: 'This username is not available.'
});
}
Here is the action creator on the client side
export const signupUser = ({ displayName, email, password, username }) => {
return (dispatch) => {
axios.post(`${API_URL}/signup`, { displayName, email, password, username })
.then((res) => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', res.data.token);
browserHistory.push('/');
})
.catch((res) => {
console.log(res.data.error);
});
};
};
What I can't seem to figure out is that I can access res.data.token in my then case but can not get hold of res.data.error in my catch case even though I can see the response come through in the network tab on chrome.
This is what I get if I log res to the console in the catch case
Error: Request failed with status code 422
at createError (eval at 150 (bundle.e3597bf….js:39), :15:15)
at settle (eval at 258 (bundle.e3597bf….js:125), :18:12)
at XMLHttpRequest.handleLoad (eval at 147 (bundle.e3597bf….js:7), :77:7)
logging res in then gives me my desired object. Any help would be appreciated.
There are two keys in the res object.
config and response
And the error message you are looking for is in res.response.data.error
Related
First of all, this is the repo website: https://github.com/TheFJS14/ck-app (you can see all code related to)
I am developing a NodeJS RESTful API with MySQL but, when I am trying to post a new User json, it report an error:
ReferenceError: User is not defined
at exports.create (C:\...\app\controllers\user.controller.js:10:18)
This is my file:
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
vvvvvvvvv
const user = new User({
nameUser: req.body.nameUser,
emailUser: req.body.emailUser
});
User.create(user, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the user."
});
else res.send(data);
});
};
I have other code references:
const UserRole = require("../models/userRole.model.js");
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const userRole = new UserRole({
nameUserRole: req.body.nameUserRole,
descriptionUserRole: req.body.descriptionUserRole
});
UserRole.create(userRole, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the user role."
});
else res.send(data);
});
};
When I move my mouse over my User model, I get this message:
https://i.stack.imgur.com/1wjwf.png
But, when I see other codes, it looks different with my mouse over them: https://i.stack.imgur.com/bqsOR.png
I probably need to change my variable name, but I prefer not.
Thanks!
I have checked your code in github, in user.controller.js you have added this line:
const UserRole = require("../models/user.model.js");
you have to change it to
const User = require("../models/user.model.js");
That's why it throws and Error that User is not defined
I have a nuxt app with express and mySQL.
Problem : I am unable to display the express res.send() custom error message on the vue side
Let's pretend I want to display infos of one single user.
Here is my back-end code :
// Find a single User with a userId
exports.findOne = (req, res) => {
User.findById(req.params.userId, (err, data) => {
if (err) {
if (err.kind === 'not_found') {
res.status(404).send({
message: `Not found User with id ${req.params.userId}.`
})
} else {
res.status(500).send({
message: 'Error retrieving User with id ' + req.params.userId
})
}
} else { res.send(data) }
})
}
And here is the Vue part
<script>
import axios from 'axios'
import appNavbar from '~/components/appNavbar.vue'
export default {
components: {
appNavbar
},
data () {
return {
userId: '',
userData: '',
errorMsg: ''
}
},
methods: {
fetchUser (evt) {
evt.preventDefault()
return axios.get('/api/users/' + this.userId)
.then((res) => {
this.userData = res.data
})
.catch((err) => {
this.errorMsg = err.toJSON()
})
}
}
}
</script>
When I give the id of a non-existing user, I want to be able to get the custom error message written in the back, and display it in the front
BUT I only get this JSON
{ "message": "Request failed with status code 404", "name": "Error" }
Does anyone have a clue ?
Thanks !
This error maybe occours because you are not setting the host when you call teh API at line:
return axios.get('/api/users/' + this.userId)
404 error is because browser not found this endpoint.
In this case, I recommend you try to call this endpoint in another tool (like Postman) and certify if your API is responding correctly.
After that, fix your call to endpoint, maybe it will be somwthing like the code bellow and try again:
return axios.get(`${your host here}/api/users/ + ${this.userId}`)
EDIT : SOLUTION FOUND
Answer found here: https://github.com/axios/axios/issues/960#issuecomment-309287911
On the vue part, the catch should return err.response, and not just err.
So in order to display your custom error message, it should be like this:
.catch((err) => {
this.errorMsg = err.response
I'm using Stripe, and trying to send a test webhook to my URL and database hosted by Firebase. When I "send test webhook," I get the following error message in the Stripe Console:
Test Webhook Error: 405
"append .json to your request URI to use the rest API"
My code is a direct copy of the tutorial: https://github.com/GaryH21/Stripe-Webhooks-Tutorial/blob/master/functions/index.js
Here is the code of my index.js:
const functions = require('firebase-functions');
const stripe = require("stripe")(functions.config().keys.webhooks);
const admin = require('firebase-admin')
admin.initializeApp();
const endpointSecret = functions.config().keys.signing;
exports.events = functions.https.onRequest((request, response) => {
let sig = request.headers["stripe-signature"];
try {
let event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret)
return admin.database().ref('/events').push(event)
.then((snapshot) => {
return response.json({ received: true, ref: snapshot.ref.toString() })
})
.catch((err) => {
console.error(err)
return response.status(500).end() // error saving to database
})
} catch (err) {
return response.status(400).end() // signing signature failed
}
})
exports.exampleDataBaseTrigger = functions.database.ref('/events/{eventId}').onCreate((snapshot, context) => {
return console.log({
eventId: context.params.eventid,
data: snapshot.val()
})
})
The only time in the tutorial and in my code that .json is used is in the line: return response.json({ received: true, ref: snapshot.ref.toString() })
Should I be appending .json onto "request" somewhere, such as in request.RawBody?
It isn't a problem with the signing keys, as that would give the 400 Error message, which I already dealt with and fixed.
I would be happy to share the code of other files in my app, but as far as I can tell none of the rest is relevant to the problem. Thank you very much.
Now, I have some server error problem.
I request to the server from react client and then server can not response.
I find an error position in my project.It comes from sequelize Database.
exports.createMemeber = (req, res) => {
console.log(req.body);
const { email, password } = req.body;
***author.findByPK(email)***
.then(res => {
res.send(email);
res.end();
})
.catch(error => {
res.status(400).send('No Validate')
})}
The main error position is
author.findByPK...
In this part there will be error in console window.
JavaScript is a case-sensitive language and the Sequelize docs show the method as findByPk (note the lower-case k).
Ref: http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findByPk
Try to change findByPK to findByPk
I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}