I have this simple post method in back-end:
router.post('/users', async function(request, response) {
try {
const userToRegister = request.body;
const user = await CreateUserService.execute(userToRegister);
return response.json(user);
} catch (err) {
console.log(err);
return response.status(401).json({ message: 'email already registered' });
}
});
At the front end i'm trying to catch the response if the users is already registered, like this:
api.post('users', user.userFields)
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err);
})
In this case, response is always undefined.
If a pass return response.json(err); in backend it works fine.
What am i missing here?
Nevermind guys, found error.
My fail was in the user catch block of CreateUserService.
Related
I'm getting this error while running this code. The API is running fine, after that it is throwing this error.
app.post('/api', async (req, res) => {
try {
channelTwo.consume(queue, async (data) => {
if (data) {
const _data = JSON.parse(data.content);
const SavedData = new User(_data);
await SavedData.save();
channelTwo.ack(data);
if (SavedData) {
res.status(200).json({ message: 'Date Saved to db', SavedData });
}
res.status(400).json({ message: 'Cant save data' });
}
res.status(400).json({ message: 'Cant find data' });
});
} catch (error) {
res.status(400).json({ message: error });
}
})
;
You have to return after calling res.status(<>).json() otherwise it will be called multiple times.
This will try to set a response header code although already json body has already been sent causing your error
I have a simple login route in express:
//login
router.post('/login',async (req,res) => {
try{
const user = await User.findOne({username: req.body.username});
console.log(user);
if (!user) {
return res.status(400).json({
success: false,
message: "username not found"
});
}
const validated = await bcrypt.compare(req.body.password,user.password);
if (!validated) {
console.log('password is wrong')
return res.status(400).json({
success: false,
message: "password not found"
})
}
const {password,...others} = user._doc;
res.status(200).json(others,{
success: true,
});
}
catch(err){
res.status(500).json(err);
}
})
I am using react for my frontend and axios to make requests:
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({type: 'LOGIN_START'});
try{
const res = await axios.post('http://localhost:5000/api/auth/login',{
username: userRef.current.value, //add the body
password: passwordRef.current.value
})
if (res.data.success) {
dispatch({type: "LOGIN_SUCCESS",payload: res.data})//if everything is fine save it into the localstorage.
}
console.log(res,"something went wrong")
}
catch(err) {
dispatch({type: "LOGIN_FAILURE"})
}
}
Now the problem is whenever i sent a status code of 400 it doesn't log the response which i want to see if i want to let the user know what's going on.
It just logs:
xhr.js:184 POST http://localhost:5000/api/auth/login 400 (Bad Request)
I want to see the content the json i am sending back.
I didn't find any similar answers regarding this.
What am i missing?
Axios 400 Bad request , you could console.log(err.response) in your catch block to get a more human-readable object.
axios errors come in three types: message, request and response.
catch(err) {
console.log(err.response);
dispatch({type: "LOGIN_FAILURE"})
}
I am using mongoose in this example. While trying to delete ,the following error is being shown to me
Cannot DELETE /5e69e2fde0fa464ee01dd68d
I cannot for the life of me figure out what is going wrong .I am a complete beginner in Node.js , MongoDB and creating RESTful APIs
The code given below is the function I am using to delete .
router.delete('/:id', getSubscriber, async (req, res) => {
try {
await res.subscriber.remove()
res.json({ message: 'Deleted Subscriber' })
} catch (err) {
res.status(500).json({ message: err.message })
}
})
and here is the getSubscriber function
async function getSubscriber(req, res, next) {
let subscriber
try {
subscriber = await Subscriber.findById(req.params.id)
if (subscriber == null) {
return res.status(404).json({ message: 'Cannot find subscriber' })
}
} catch (err) {
return res.status(500).json({ message: err.message })
}
res.subscriber = subscriber
next()
}
Any help is appreciated. Thank you for your time.
router.delete('/:id', getSubscriber, async (req, res) => {
try {
//Here try creating an instance of your model.
//I think your schema is named subscriber so
const deleteSuscriber = await Suscriber.remove({_id:req.params.id});
res.json(deleteSuscriber);
} catch (err) {
res.status(500).json({ message: err})
}
});
Here express will put the variable in req.params form the incoming request.
Hope this works!!
Here you can find the documentation on making CRUD Rest API
I'm having a little issue. I'm developing an app and I created API with node.js(using express). Right now I'm trying to send my error objects from node to react but for some reason I cannot get it. I can see the object in the network tab but I want to use it, like console it to the client.
back-end:
app.post('/api/users/login', async (req, res) => {
try {
const user = await User.findByCredentials({ ...req.body });
const token = await user.generateAuthToken();
res
.cookie('w_auth', token)
.status(200)
.send({ user, token });
} catch (error) {
res.status(400).send({ success: false, error: 'some error' });
}
});
client-side:
loginUser:
export const loginUser = dataToSubmit => {
return axios.post(`${USER_SERVER}/login`, dataToSubmit);
};
loginUser(dataToSubmit)
.then(res => {
console.log(res);
dispatch({ type: 'SET_USER', user: res.data.user });
})
.catch(error => {
console.log(error);
});
I tried also just send a respond without error from back-end which also didn't work.
picture of what I get:
network tab:
You can catch it the below way.
axios
.post(url, data)
.then(response => {
//You get success response here.
})
.catch(err => {
//Error response here
});
I am new to javascript and I need to handle constraint error in sequelize. I searched related to this topic everywhere, but still, I couldn't get a proper workable answer. My attempt it as follows.
app.post('/api/users', (req, res) => {
try {
console.log(req.body);
User.create(req.body)
.then(user=> res.json(user));
} catch (error) {
console.log("Error: "+error);
}});
Here couldn't catch the exception yet. For a valid user input it is able to post the request. So I just need to know a way to handle the exception.
Was looking around for an answer for this, but was not really satisfied with the two given. If you are looking to return a correct response such as a 403 this is the solution I have came up with.
app.post('/api/users', async (req, res) => {
try {
console.log(req.body);
var user = await User.create(req.body)
return res.status(200).json({ status: 'success', result: res.json(user) })
} catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') {
res.status(403)
res.send({ status: 'error', message: "User already exists"});
} else {
res.status(500)
res.send({ status: 'error', message: "Something went wrong"});
}
}
});
You can use Promise with .then().catch(), or use async/await with try/catch
This is Promise
app.post('/api/users', (req, res) => {
console.log(req.body);
User.create(req.body)
.then(user=> res.json(user))
.catch(err => console.log(err))
});
This is async/await
app.post('/api/users', async (req, res) => {
try {
console.log(req.body);
const user = await User.create(req.body);
res.json(user);
} catch (error) {
console.log("Error: "+error);
}
});
Looks like you're mixing two different styles. If you're using then(), then the try catch block is unnecessary:
app.post('/api/users', (req, res) => {
console.log(req.body)
User.create(req.body)
.then(user => res.json(user))
.catch(error => console.log('Error: ' + error))
})
The other style would be using the async package. With async, your code would look like this:
app.post('/api/users', async (req, res) => {
console.log(req.body)
try {
const user = await User.create(req.body)
res.json(user)
}
catch (error) { console.log('Error: ' + error) }
})
Both methods have their advantages and disadvantages that go beyond this snippet and lot of people use both as appropriate, for example the await approach works only inside a function declared with async like in the second example :async (req, res). In such cases, using then() style promise handling is a better approach