I am fetching a big problem with axios in my project. I used axios for fetching data in getServerSideProps. but is it showing 'Request failed with status code 404', in the same time i also used axios in useEffect where it get data from api.
export async function getServerSideProps() {
try {
const ApiUrl = apiBaseUrl + "/api/my-url";
const homeData = await axios
.get(ApiUrl)
.then((response) => {
return response.data;
})
.catch((error) => {
return error.message;
});
return {
props: {
homeData: homeData, // its is return Request failed with status code 404
error: false,
ApiUrl: ApiUrl,
},
};
} catch (e) {
return {
props: {
error: true,
homeData: null,
message: e.message,
},
};
}
}
through i cna not get data from getServerSideProps i used useEffect
useEffect(() => {
if (typeof props.homeData === "string") {
console.log(props); // it is showing error 'Request failed with status code 404'
} else if (props.homeData) {
console.log(props.homeData);
// setData(props.homeData);
} else {
axios
.get(apiBaseUrl + "/api/my-url")
.then((response) => {
seteData(response.data);
})
.catch((error) => {
console.log(error);
});
}
}, [props]);
I have a Cloud Firestore function trigger "onCreate". Depending on the value of a given field, I would like it to either update some documents via a transaction and to copy the created document as a record in Algolia, or to execute a completely different transaction. There are therefore several conditions and I am not sure that I am returning promises correctly, as sometimes the function is not copying the record in Algolia when expected.
I paste a simplified version of the code in case someone can help.
exports.createArticle = functions.firestore.document('articles/{articleId}').onCreate(async (snap, context) => {
const newDocData = snap.data()
if(newDocData) {
const userCreatorId = newDocData.createdBy
const userDocRef = imported.db.collection('users').doc(userCreatorId)
if(newDocData.type === 1) {
newDocData.objectID = newDocData.id
indexAlgolia.saveObject(newDocData)
.then(() => {
console.log('Article saved in Algolia with id:', newDocData.objectID )
})
.catch(err => {
console.log('ERROR while ADDING object inAlgolia:', err)
})
return imported.db.runTransaction(async t => {
// do some work
const userDoc = await t.get(userDocRef)
const userData = userDoc.data()
if (userData && userData.field1 > 0) {
t.update(userDocRef, {field2: true})
}
}).then(result => {
console.log('Transaction success')
}).catch(err => {
console.log('Transaction failure:', err)
})
}
else {
const colOneRef = imported.db.collection('colOne')
colOneRef.where('field2', '==', newDocData.field3).limit(1).get().then(snapshot => {
return imported.db.runTransaction(async t => {
if (snapshot.empty) {
t.update(userDocRef, {field3: false})
}
const decrement = imported.fieldValue.increment(-1)
t.update(userDocRef, {field4: decrement})
}).then(result => {
console.log('Transaction success')
}).catch(err => {
console.log('Transaction failure:', err)
})
}).catch(() => 'Error while querying colOneRef')
}
}
})
When you have multiple async/then calls you canmake them await the result and run them as if they are synchornous but from your code I see that the second doesn't depent on the first one so you can put them in a Promse.all() to make the function finish faster because they will run in parallel. Your code would look like this:
xports.createArticle = functions.firestore
.document("articles/{articleId}")
.onCreate(async (snap, context) => {
const newDocData = snap.data();
if (newDocData) {
const userCreatorId = newDocData.createdBy;
const userDocRef = imported.db.collection("users").doc(userCreatorId);
if (newDocData.type === 1) {
newDocData.objectID = newDocData.id;
const firstPromise = indexAlgolia
.saveObject(newDocData)
.then(() => {
console.log(
"Article saved in Algolia with id:",
newDocData.objectID
);
})
.catch((err) => {
console.log("ERROR while ADDING object inAlgolia:", err);
});
const secondPromise = imported.db
.runTransaction(async (t) => {
// do some work
const userDoc = await t.get(userDocRef);
const userData = userDoc.data();
if (userData && userData.field1 > 0) {
t.update(userDocRef, { field2: true });
}
})
.then((result) => {
console.log("Transaction success");
})
.catch((err) => {
console.log("Transaction failure:", err);
});
return Promise.all([firstPromise, secondPromise]);
} else {
const colOneRef = imported.db.collection("colOne");
return colOneRef
.where("field2", "==", newDocData.field3)
.limit(1)
.get()
.then((snapshot) => {
return imported.db
.runTransaction(async (t) => {
if (snapshot.empty) {
t.update(userDocRef, { field3: false });
}
const decrement = imported.fieldValue.increment(-1);
t.update(userDocRef, { field4: decrement });
})
.then((result) => {
console.log("Transaction success");
})
.catch((err) => {
console.log("Transaction failure:", err);
});
})
.catch(() => "Error while querying colOneRef");
}
return
}
});
I'm using passport with bookshelf, and im having issues inserting a user in the database.
I'm using postman, and it shows that a user has been added to the db, but its not.
There doesn't seem to be much information about bookshelf, passport, and postgres used together. So it makes finding solutions like this hard.
routes/users
router.post('/register', (req, res, next) => {
passport.authenticate('register', (err, user, info) => {
if(err){
console.log(err)
}
if(info !== undefined){
console.log(info.message)
res.status(403).send(info.message)
}else{
req.logIn(user, err => {
const data = {
username: req.body.username.trim(),
password: req.body.password.trim(),
email: req.body.email.trim()
}
console.log(data);
User.forge({
username: data.username
}).fetch().then( (user) => {
console.log('user creatd in db');
res.status(200).send({
message:'user created'
})
})
})
}
})(req, res, next);
});
passport.js
import passport from 'passport';
import LocalStrategy from 'passport-local';
import User from '../models/User';
import bcrypt from 'bcrypt';
import JWTstrag from 'passport-jwt';
import ExtracJWT from 'passport-jwt';
const JWTstrategy = JWTstrag.Strategy
const ExtractJWT = ExtracJWT.ExtractJwt
const Local = LocalStrategy.Strategy
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: process.env.JWT_SECRET,
};
passport.use('jwt', new JWTstrategy(opts, (jwt_payload, done) => {
try{
User.forge({username: jwt_payload._id})
.fetch()
.then( (user) => {
if(user){
console.log('user found in db in passport');
done(null, user)
}else{
console.log('user not found in db');
done(null, false)
}
})
} catch(err){
done(err)
}
}))
passport.use(
'register',
new Local(
{
usernameField: 'username',
passwordField: 'password',
// passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, 12).then(hashedPassword => {
const user = new User({
username: req.body.username,
password: hashedPassword,
email: req.body.email
})
user.save().then( () => {
res.status(200).send('user created')
return done(null, user);
})
});
}
});
} catch (err) {
return done(err);
}
},
),
);
// passport.use(new Local ( (username, password, done) => {
// User.findOne({username: username} , (err, user) =>{
// if(err){
// return done(err)
// }
// if(!user){
// return done(null, false, {message: "Incorrect username."})
// }
// if(!user.validPassword(password)){
// return done(null, false, {message: 'Incorrect password'})
// }
// return done (null, user)
// })
// }))
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
User
.forge({id: user})
.fetch()
.then((usr) => {
done(null, usr);
})
.catch((err) => {
done(err);
});
});
main.js
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import passport from 'passport';
import session from 'express-session';
import './config/passport';
const app = express();
app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(bodyParser.urlencoded({ extended:false}));
app.use(session({
saveUninitialized: false,
resave:false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
secret : process.env.JWT_SECRET,
}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.use('/users', userRoute);
app.use(() => (req, res, next) =>{
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
//build mode
// app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })
// module.parent prevents the
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
}
export default app;
Fixed it, there were a number of errors.
One being the
done is not a function
Which will be fixed by uncommenting
passReqToCallback: true,
two being res thats not supposed to be in the passport.js file but route file.
so remove
res.status(200).send('user created')
Now everything should be working.
passport.js
passport.use(
'register',
new Local(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, 12).then(hashedPassword => {
const user = new User({
username: req.body.username,
password: hashedPassword,
email: req.body.email
})
user.save().then( () => {
return done(null, user);
})
});
}
});
} catch (err) {
return done(err);
}
},
),
);
routes/users
router.post('/register', (req, res, next) => {
passport.authenticate('register', (err, user, info) => {
if(err){
console.log(err)
}
if(info !== undefined){
console.log(info.message)
res.status(403).send(info.message)
}else{
req.logIn(user, err => {
const data = {
username: req.body.username.trim(),
password: req.body.password.trim(),
email: req.body.email.trim()
}
console.log(data);
User.forge({
username: data.username
}).fetch().then( (user) => {
console.log('user creatd in db');
res.status(200).send({
message:'user created'
})
})
})
}
})(req, res, next);
});
I m trying to get information through the facebook sdk but so far I am getting only the id and the name of the user. I do have granted the premission but still the email is not popping out like name and id.
I try to console.log(result.email) but i got undefined .
Any help would be appreciated.
Thanks in advance
import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken ,GraphRequest, GraphRequestManager} from 'react-native-fbsdk';
export default class Login extends Component {
render() {
return (
<View>
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
console.log(result.email)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
}
i'm trying to do login to my app with facebook,
i installed the cordova facebook plugin
and this my code but i get error on Promise
this is my code(actually i just copied it from tutorial that say it works for him)
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import {Http, Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
declare const facebookConnectPlugin: any;
#Component({
templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
posts:any;
constructor(public platform: Platform, private navCtrl: NavController,private http: Http)
{ this.platform = platform;
this.http = http;
}
fblogin()
{
this.platform.ready().then(() => {
this.fblogin1().then(success => {
console.log("facebook data===" + success);
alert("facebook data===" + success);
this.http.post('http://localhost/facebook.php',success)
.map( res =>res.json()).subscribe(data => {
if(data.msg=="fail")
{
console.log('Login failed');
alert("Invalid username and password");
return;
}
else
{
console.log(' login Sucessfully facebook');
}
});
}, (error) => {
alert(error);
});
});
}
fblogin1(): Promise<any>
{
return new Promise(function(resolve,reject)
{
facebookConnectPlugin.login(["email"], function(response)
{
alert(JSON.stringify(response.authResponse));
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,email,gender',[],
function onSuccess(result)
{
//alert(JSON.stringify(result));
//console.log(JSON.stringify(result));
resolve(JSON.stringify(result));
},
function onError(error)
{
alert(error);
}
);
},
function(error)
{
alert(error);
})
});
}
}
if anyone know another way i would like to know.
i solve this issue by changing the login function to this code
facebookLogin(){
Facebook.login(['email']).then( (response) => {
let facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
var that = this;
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
that.userProfile = JSON.stringify(success);
that.nav.setRoot(HomePage);// after login go to HomePage
})
.catch((error) => {
console.log("Firebase failure: " + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}