Image is not defined (Firebase storage - React Native) - image

The problem:
I am able to successfully upload an image to firebase storage, but when I try to sign-out, then sign-in again, I am stucked on the log-in page. and after few minutes this error appears
This is my code on fetching the image and log-in
if (currentUser != null) {
uid = currentUser.uid;
const db = firebase.firestore();
const docRef = db.collection("users").doc(uid);
console.log("uid")
console.log(uid)
console.log("currentUser")
console.log(currentUser)
console.log("docRef")
console.log(docRef)
docRef.get().then((doc) => {
console.log("doc");
console.log(doc);
if (doc.exists) {
console.log("Document data:", doc.data());
const userData = doc.data();
const imageRef = firebase.storage().ref(`/userProfilePictures/${uid}`).child('profile.jpg');
imageRef.getDownloadURL().then(function(url) {
dispatch({ type: GET_PROFILE_PICTURE, payload: url })
dispatch({ type: GET_USER_DATA, payload: userData});
Actions.home();
}).catch((error) => {
dispatch({type: GET_PROFILE_PICTURE, payload: ''})
console.log(error);
})
} else {
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
}else {
console.log('something went wrong');
}
})
.catch((error) => {
loginUserFail(dispatch)
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorMessage);
});
After loggin in again, it seems that the user is authenticated, but It can't execute this line docRef.get().then((doc) => { there is no error on the console.log.
And then if you try to reload again, then sign-in again you can see the newly uploaded image.

Related

NextJs - Node - API resolved without sending a response for /api/xxx

I have a nextjs app with a backend api where I am sending an email out.
I have seen a couple of other posts with the same issue, have tried their resolutions and not sure what I am missing.
Any insight is appreciated.
The code in the API is below.
const nodemailer = require('nodemailer');
export default function (req, res) {
const mailData = {
from: 'xxxxx',
to: req.body.email,
subject: 'Message to Full On Consulting',
text: req.body.message,
html: '<div>'+req.body.message+'</div>'
}
sendMail(mailData)
.then((result) => {
console.log('Email sent...', result);
res.status(200).json({ status: 'SUCCESS' })
})
.catch((error) => console.log('Error ... ' + error.message));
}
async function sendMail(mailData) {
try {
let transport = nodemailer.createTransport({
host: "mail.xxxxxxxxxx.com",
port: 587,
secure: false,
auth: {
user: process.env.GMAIL_UID,
pass: process.env.GMAIL_PW
}
});
const result = await transport.sendMail(mailData)
return result;
} catch (error) {
console.log("CATCH ERROR: " + error)
return error;
}`enter code here`
}
I wrapped the sendmail call in a promise and that seems to have worked.
var promise = new Promise( (resolve, reject) => {
let result = transport.sendMail(mailData);
});
promise.then( result => {
console.log("PRomise Success ...");
}, function(error) {
console.log("Promise Failure...");
});

Progressive Web Apps laravel cache issue

I am working with PWA for my laravel project, My PWA app working fine, my website run in https only but When i logged in my website shows my old logged user details how can i solve this issue?
I am afraid my website also run based on cache memory
In localhost PWA icon not showing in my browser how can i solve in localhost
here i added service provider js file
// Cache API
const staticCacheName = 'app-shell-v2.0';
const filesToCache = [
// Files
'.',
//css files and js file
];
self.addEventListener('install', event => {
console.log('Installing worker to cache static assets');
self.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', event => {
console.log('Activating new worker...');
const cacheWhitelist = [staticCacheName];
self.clients.claim();
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
// exclude directories from cache
/*if (event.request.url.match('^.*(\/admin\/).*$','^.*(\/users\/show\/).*$')) {
return false;
}
if (event.request.url.endsWith('authenticate')) {
return false;
}*/
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request)
.then(response => {
if (response.status === 404) {
return caches.match('https://site_url/404.html');
}
return caches.open(staticCacheName)
.then(cache => {
cache.put(event.request.url, response.clone());
return response;
});
});
}).catch(error => {
console.log('Error, ', error);
return caches.match('https://site_url/offline.html');
})
);
});

Vue js PATCH http://127.0.0.1:8000/api/auth/profile 401 (Unauthorized)

I have a modal where I can create edit users. But when I click on the submit button I got a 401 error.
and I want to change the name without update page
The method looks like this:
if(token){
this.preformUpdate();
}
},
methods: {
preformUpdate: function() {
this.loading = true;
this.msgupdate = "Updated your profile";
this.alert = true;
axios
.patch("/profile", {
name: this.name,
token: this.token
})
.then(response => {
const name = localStorage.setItem("name", response.data.user.name);
this.email = localStorage.getItem("email");
console.log(response.data.user.name);
this.loading = false;
})
.catch(error => {
console.log(error);
this.error = error.message;
this.loading = false;
});
}
}

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

Google recaptcha v3 always returning error

Following the instructions I get a valid token from my front end (can see in dev tools):
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// this is what I POST to my API
So in my React front end:
send = (event) => {
event.preventDefault()
this.setState({ busy: true })
window.grecaptcha.ready(() => {
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// successfully get token
const payload = {
token,
name: this.state.name,
to: this.props.to,
email: this.state.email,
message: this.state.message,
}
// now I'm sending the payload to my API
// My API
update(`${api}/contact/`, {
method: 'POST',
body: JSON.stringify(payload)
}, null)
.then(data => {
this.setState({ busy: false, result: 'Email sent' });
})
.catch(error => {
this.setState({ busy: false, error: error.message });
});
})
})
}
my API controller
async function verifyCaptcha(token) {
return await axios.post('https://www.google.com/recaptcha/api/siteverify', {
secret: process.env.CAPTCHA_PKEY,
response: token
})
}
async function contact({ token, to, name, email, message }) {
const result = await verifyCaptcha(token)
if (!result || !result.data || !result.data.success) {
// always get an error here
throw new Error('Invalid captcha')
}
let targetEmail = 'default#emailaddress'
if (to !== 'admin') {
const user = await User.findOne({ username: to }, { email }).exec()
if (!user) {
throw new Error('User does not exist')
}
targetEmail = user.email
}
// rest of send
}
On my API POST endpoint sends to https://www.google.com/recaptcha/api/siteverify with the body of:
{
secret: process.env.CAPTCHA_PKEY,
response: token
}
Yet I always get "missing-input-response", "missing-input-secret" error. Is this because v3 is new? Still bugs?
Realised in the documentation it states "post params" not post body haha.

Resources