I'm using .then(jsonResponse => after a fetch function, i stringfied it and logged it into the console to see if the api returns the confirmation key as "success", even though it returns as success the statement:
if (jsonResponse.confirmation === "success") {
this.props.navigation.navigate("main");
}
Is not working, it doesn't navigate to the 'main' screen, does anyone know how to fix this? I've been searching the forum for an answer but couldn't find, here's how the code is organized:
register() {
fetch(config.baseUrl + "signup", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(this.state.credenciais)
}) //all of this works, since it connects to the api and registers the user with its credentials
.then(response => response.json())
.then(jsonResponse => {
console.log(JSON.stringify(jsonResponse)) //this returns as success
console.log(response) // returns as undefined
if (jsonResponse.confirmation === "success") {
this.props.navigation.navigate("main");
} else {
throw new Error({
message: "Algo ocorreu de errado, por favor tente novamente"
});
}
})
.catch(err => {
console.log(err.message);
});
}
I commented the parts where I couldn't figure it out, and in the api I have as the route:
router.post("/signup", function(req, res) {
console.log(req.body);
turbo
.createUser(req.body)
.then(data => {
res.json({
confirmation: "success",
data: data
});
})
.catch(err => {
res.json({
confirmation: "fail",
message: err.message
});
});
});
As you can see, I have confirmation: success if everything goes right, the code above works and registers the user but doesn't navigate to the 'main' screen, does anyone know what is wrong with my code?
Edit: As asked below here's the console.log(JSON.stringify(jsonResponse))
{"confirmation":"success","data":{"firstName":"","lastName":"","email":"testestes#aol.com","username":"","bio":"","image":"","timestamp":"2018-11-03T16:16:00.855Z","stripe":{},"schema":"user","id":"5bddc9c050edeb001431cb2e"}}
Also, the register() is called in a TouchableOpacity:
<TouchableOpacity
onPress={() => {
this.register();
}}
>
Related
I am trying to set up an edit feature to edit a post. Right now I am trying to update a specific post by ID and then I'll make it dynamic.
I can get axios to send the PUT request but I don't receive any indication that it is received on the router. Also the ID I have set it showing up correctly in the URL.
I'm not sure how to send the data over to the router so it can find the ID.
Edit component
function handleSubmit(event){
event.preventDefault()
axios ( {
url: `/api/${props.data[0]._id}`,
method: 'PUT',
headers: { "Content-Type": "multipart/form-data" },
id: props.data[0]._id
})
.then(() => {
console.log(`data has been sent to the server from axios: ${props.data[0]._id}`)
})
.catch(() => {
console.log('Data could not be sent from axios')
})
}
Router
router.put('/:id', async (req, res) => {
try {
const updatedGratitude = await PostGratitude.findByIdAndUpdate(req.params.id)
res.status(200).json(updatedGratitude)
} catch (err){
next(err)
}
})
if you are editing a post then you should send the data in the request as well
like a title: "" and description: "" or something and in the in the router, you could write something like this :
function handleSubmit(event) {
event.preventDefault()
axios({
url: `/api/${props.data[0]._id}`,
method: 'PUT',
headers: { "Content-Type": "application/json" },
data: {
title: '',
description: ''
}
})
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
})
}
you need to pass the arguments as to what to update as well, here is an example of a code that I wrote
router.put('/updatentry/:id',fetchuser, async (req, res) => {
var success = false
try {
const { title, description } = req.body
let newentry = { title: title , description: description
}
let old_entry = await Journal.findById(req.params.id);
if (!old_entry) {
return res.status(404).send({ success, error: 'Not Found'})
}
const update_entry = await Journal.findByIdAndUpdate(req.params.id, { $set: newentry }, { new: true })
return res.send(res: update_entry)
} catch (error) {
return res.status(500).send(error: 'Internal Server Error')
}
})
This is because you forgot the update body on method. Try this:
PostGratitude.findByIdAndUpdate(req.params.id, req.body)
instead of :
await PostGratitude.findByIdAndUpdate(req.params.id)
Because mongoose can not know what to update :D
I have created a function that makes a call to an api shown below. I am displaying the message from setMessage on the front end. For some reason when there is no error the .catch block message flashes in setMessage() and then the setMessage() finally ends with the correct message from .then().
I'm not sure why this is.
function handleCoupon(e) {
e.preventDefault();
setMessage("");
setLoading(true);
fetch(`${process.env.NEXT_PUBLIC_SERVER_API}/subscription/coupon/get`, {
method: "POST",
body: JSON.stringify({
appliedCoupon: couponCode.toLowerCase().trim(),
}),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((data) => {
console.log(data);
if (data.coupon === true) {
setMessage(data.message);
setLoading(false);
} else {
setMessage(data.message);
setLoading(false);
}
})
.catch(
(error) => console.log(error.message),
setMessage("Something went wrong, please contact support")
);
}
The .catch only accept single function as parameter, and you are passing 2 of them:
(error) => console.log(error.message)
setMessage("Something went wrong, please contact support")
Try merging them into 1 function, e.g.
.catch((error) => {
console.log(error.message);
setMessage("Something went wrong, please contact support");
});
My client is Vue.js using a Vuex store. I am using passport.js for authentication on the server side. Login and account registration is working. Checking mongodb shows new data. But express is sending an undefined response to the client. This is my first major javascript project so I'm hoping it's something simple my eyes just can't see yet.
client: api.js
export async function registerUser(user) {
console.log("api to register user");
console.log(user);
const route = `${api}/register`;
return fetch(route, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(response => {
console.log(response.json());
return response.json();
})
.then(json => {
console.log(json);
return json;
})
.catch(err => {
console.error(err);
});
}
client: index.js (vuex store where res is undefined)
actions: {
async register(state, user) {
apis.registerUser(user).then(res => {
if (res.success) {
this.dispatch("loadUser");
alert("successfully registered");
}
});
},
async loadUser() {
apis.getUser().then(res => {
this.commit("setUser", res.user);
});
}
}
server: app.js
app.post('/api/v1/register', function(req, res) {
const success = true;
Users=new User({email: req.body.email, username : req.body.username});
console.log(req.body);
User.register(Users, req.body.password, function(err, user) {
if (err) {
console.log('account could not be saved');
success = false;
} else {
console.log('account saved');
}
})
res.send({success: success});
});
fetch error printing to console
The server console.logs in the app.js route indicate the req.body has the right data and user account is saved successfully. No errors occur on res.send but the client gets an undefined response.
After much banging my head against the table and some outside assistance, I found a solution. I had two main issues.
I was not preventing the default on the submit button so the form was refreshing before the request was properly handled.
Mishandling of javascript promises.
Working code below:
api.js
export function registerUser(user) {
console.log("api to register user");
console.log(user);
const route = `${api}/register`;
return fetch(route, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(response => {
console.log(response.json());
return response.json();
})
}
index.js (vuex store)
actions: {
register(state, user) {
apis.registerUser(user).then(res => {
if (res.success) {
alert("successfully registered");
}
}).catch(err => {
console.error(err);
});
}
}
app.js code remained the same
I can't seem to get the correct response headers when my code enters bcrypt.compare. I thought it was a cors issue at first but I still get the correct response if I entered the wrong and "user does not exist" is displayed.
Here's my api server side code in express
router.post("/api/signIn", (req, res) => {
const { user, password } = req.body;
const queryString = "SELECT * FROM users WHERE user_id = ?";
db.query(queryString, [user])
.then(result => {
if (result.length > 0) {
const hash = result[0].password;
//here bcrypt.compare works server side or with cURL but won't set the response headers in the browser
bcrypt
.compare(password, hash)
.then(same => {
if (same === true) {
console.log("correct password");
res.status(200).json({
code: 200,
message: "correct password"
});
} else {
res.status(401).json({
code: 401,
message: "incorrect password"
});
}
})
.catch(err => console.log(err));
} else {
//this one works though and i can get the response in the browser so it can't be a cors issue
console.log("user does not exist");
res.status(200).json({
code: 401,
message: "User does not exist"
});
}
})
.catch(err => {
console.log("error" + err.message);
});
});
and this is the test function i use in react
const signIn = () => {
fetch("http://localhost:5000/api/signIn", {
method: "POST",
body: JSON.stringify({
user: userName,
password: password
}),
headers: {
"Content-Type": "application/json"
},
})
.then(res => res.json())
.then(response => alert(response.code + response.message))
.catch(err => alert(err));
};
so if i entered the wrong username that is not in the database, the alert function would show (code401User does not exist) but if i entered the correct user bcrypt.compare() doesn't seem to set the response for both correct and incorrect passwords and i would get (TypeError: failed to fetch). testing the api in cURL works though.
Got it, I forgot to put event.preventDefault() on the fetch function.
I'm pretty new to node and everything that happens around, but I'm trying to make a little admin panel. There will be a login page and after login if the user is an admin the page will redirect to dashboard.ejs.
I suppose I didn't do it the correct way because what I did don't work.
Let me show you what I did :
Let's start with my main routes for admin. So these can be accesses with /admin and /admin/dashboard. If I just go to /admin the page loads normally with the login forms.
router.get('/', (req, res) => {
res.render('../views/admin/admin.ejs')
})
router.get('/dashboard', admin_check, (req, res) => {
res.render('../views/admin/dashboard.ejs')
console.log('dashboard rendered...')
})
I have a simple login button that will do some checks in the database and finally run this to redirect to the dashboard :
fetch('/admin/dashboard', {
headers: {
auth_token: sessionStorage.getItem('token')
}
})
This will correctly trigger and let the console.log() run that comes from here :
router.get('/dashboard', admin_check, (req, res) => {
res.render('../views/admin/dashboard.ejs')
console.log('dashboard rendered...')
})
The thing is, the dashboard isn't loaded while the res.render() in fact executed.
There is an error in console though :
The resource from “http://localhost:8080/admin/scripts/admin-auth.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
I looked up a little bit what this was but I don't really understand anything about it.
Here is my full admin-auth.js file :
$('#login_form').submit(e => {
e.preventDefault()
fetch('/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
email: $('#login_email').val(),
password: $('#login_password').val()
})
})
.then(res => res.json())
.then(data => {
if (data.status === 200) {
sessionStorage.setItem('token', data.token)
sessionStorage.setItem('user', data.user)
fetch('/api/user', {
headers: {
auth_token: data.token
}
})
.then(res => res.json())
.then(data => {
if (data.user.admin) {
fetch('/admin/dashboard', {
headers: {
auth_token: sessionStorage.getItem('token')
}
})
}
})
} else {
console.log(data.error)
}
})
})
EDIT: So I used this instead :
res.sendFile(process.cwd() + '/src/views/admin/dashboard.ejs')
But the page still don't appear. Errors are gone and in the network management I get a 200 response but that's it