cant get current user with axios get - axios

In my API is the current user (I have logged in with passport) but when I make an Axios get request the data field is empty. I absolutely don't know what to do :(
<script>
import axios from "axios"
export default {
name: 'Home',
components: {
},
data: function() {
return {
user: axios.get('http://127.0.0.1:3000/api/').then(response => this.user = response)
}
},
methods: {
}
}
</script>
Here is the output:
Here is my API:
Edit: Here is my Backend File:
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const cors = require('cors')
const passport = require('passport')
let LocalStrategy = require('passport-local').Strategy;
const session = require('express-session')
var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const port = 3000
app.use(cors({
methods:['GET','POST'],
credentials: true
}))
app.use(express.static('public'))
//Passport setup
app.use(session({
secret: 'test',
resave: false,
saveUninitialized: false,
secure: true
}))
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
const apiRoutes = require('./apiRoutes')
app.use(cors())
app.use('/api', apiRoutes)
// connect to database
mongoose.connect('mongodb+srv://#cluster0.dhsiv.mongodb.net/test?retryWrites=true&w=majority',
{useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log('Erfolgreich connected')
})
app.listen(port, () => {
console.log('server is running on port '+port)
})
module.exports;
I hope someone can help me. Thanks a lot guys :)
i have also change my data and run the axios get in mounted but it doesnt change anything.
Routes:
const { _ } = require('core-js');
const { Mongoose } = require('mongoose');
const { find, where } = require('./models/userModel');
const userModel = require('./models/userModel');
let router = require('express').Router();
const bcrypt = require('bcryptjs')
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
let jwt = require('jsonwebtoken');
const { static } = require('express');
require('./passportConfig')
router.get("/", (req, res) => {
res.json({
user: req.user
});
});

Related

how to use connect-mongo version 4x with express-session. I'm getting errors

I am getting errors while trying to save sessions on MongoDB
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const { connection } = require('mongoose');
app.use(
session({
secret: 'some secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client: connection,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
})
);
Error:
C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126
.db(options.dbName)
^
TypeError: con.db is not a function
at C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126:18
Here is the Solution:
const express = require('express');
const session = require('express-session');
require('dotenv').config();
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const PORT = process.env.PORT || 3001;
const MONGO_URI = process.env.MONGODB;
const app = express();
//connectDB should return the client conn.connection.getClient();
const client = connectDB().then((mClient) => {
app.listen(PORT, () => console.log('Server running...');
return mClient;
}).catch(err => console.log(err));
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(
session({
secret: 'some-secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client,
}),
})
);
app.get('/', (req, res, next) => {
res.send('<h1>Hello World (sessions)</h1>');
});
```

PostgreSQL \ Vue - Not able to get data from the Database (PostgreSQL) using Express and Vue on Front-End

This is What I am getting on the Console of Chrome
I am Using Vue.js (vue-resource) and Express with PostgreSQL
I have a list on the server Side which I want to get on the items (and display on the Webpage)
but I am not getting anything
Following is the Vue file code
<script>
export default {
name: 'order',
data () {
return {
orderOpt: 'Deliver',
orderType: 'State',
items: []
}
},
created () {
this.$http.get('localhost:3000/items').then(response => {
this.items = response.body
}, response => {
setTimeout(function () {
alert('The Server is not Running/items')
}, 10000)
})
},
computed: {
total () {
let sum = 0
for (let i = 0; i < this.items.length; i++) {
sum += parseInt(this.items[i].quantity)
}
return sum
}
},
methods: {
itemsUpdate (value) {
this.items.forEach((item, i) => {
console.log(value)
item.inStock -= item.quantity
item.quantity = 0
})
this.post(this.items)
},
post (Data) {
this.$http.post('localhost:3000', Data)
}
},
watch: {
}
}
</script>
As I am using Express on the server side
This following code is present in the index.js
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors')
const app = express();
const Joi = require('joi');
const Data = require('./Data.json');
const { Pool, Client } = require('pg');
const pool = require('./db');
const port = process.env.USER || 3000;
//middleware
app.use(express.json());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(cors())
//DATA
const getItems = (req, res) => {
pool.query('SELECT * FROM data', (err, results) => {
if (err) {
throw err
}
res.status(200).json(results.rows)
})
}
app.listen(port, function () {
console.log(`Server Starts on ${port}`);
});
//Requests
app.get('/', (req, res) => {
res.json({Welcome: 'API Created'})
})
app.get('/item', async (req, res) => {
res.status(200).send(Data);
});
app.get('/items', getItems)
app.post('/items', (req, res) => {
try {
const items = [req.body.name, req.body.inStock, req.body.quantity];
const newItems = pool.query(
"INSERT INTO data VALUES ($1, $2, $3) RETURNING *",
items
).then(()=> {
console.log(newItems);
});
} catch (e) {
console.error(e);
}
pool.end();
});

MongoDB: No write concern mode named 'majority a' found in replica set configuration

I am working through a traversy media tutorial and I've come across an error (in the title) that I'm not familiar with. I've been trying to learn about this but I'm still stumped as to why its appearing and where its coming from. Furthermore, I havent found any direct matches for this issue.
Here is the code in question, the catch at the bottom is returning the error.message.
edit: its also worth noting that I am able to successfuly add users to my database. So, it runs through the try block but also the catch ... so thats a big confusing. The only response I am getting on postman is the server error 500 message from the catch block.
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const User = require('../../models/User');
// #route GET api/users
// #desc Test route
// #access Public
router.post(
'/',
[
check('name', 'Name is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 }),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
// see if user exists
if (user) {
return res.status(400).json({
errors: [{ msg: 'User already exists' }],
});
}
// get users gravatar
const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm',
});
user = new User({
name,
email,
avatar,
password,
});
// encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// return jsonwebtoken
return res.send('User registered');
} catch (error) {
console.log(error.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
The User schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
connection configuration:
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log('Connected to MongoDB');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;

MongoDb Atlas: UnhandledPromiseRejectionWarning - MongooseTimeoutError

I am new in mongodb and currently following this article: https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1
I am using mongoDB atlas as a course suggested and also whitelist my IP in it as many answers suggested.
File: .env
ATLAS_URI=mongodb+srv://sagar:<mypass>#cluster0-2gcdi.gcp.mongodb.net/test?retryWrites=true&w=majority
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
user.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
routes:users.js
const router = require('express').Router();
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
currently its showing Error in console:
UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms
at new MongooseTimeoutError (C:\Users\sagar\OneDrive\Desktop\nodejs\mern-exercise-tracker\backend\node_modules\mongoose\lib\error\timeout.js:22:11)
I am also testing my api in postman where its showing:
Could not get any response
There was an error connecting to http://localhost:5000/users/add.
Error of my screenshot:

ExpressJS is redirecting after POST

I have following problem. My server which is written in ExpressJs (used MongoDB as database) is redirecting my page after registration ( POST method ). Why?
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const morgan = require('morgan');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const port = process.env.PORT || 9090;
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');
const router = express.Router();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.get('/', function(req, res) {
res.json({
"get | post": "/users"
});
});
app.use('/api', router);
require('./routes/users')(app,router);
app.listen(port);
console.log('Started server on port ' + port);
users.js
const User = require('../models/user');
module.exports = function(app, router){
app.post('/api/users',function(req, res) {
var user = new User();
user.name = req.body.name;
user.surname = req.body.surname;
user.email = req.body.email;
user.age = req.body.age;
user.login = req.body.login;
user.password = req.body.password;
user.created_at = req.body.created_at;
user.update_at = req.body.update_at;
user.save(function(err) {
if (err)
res.send(err);
res.json({
name: user.name,
surname: user.surname,
email: user.email,
age: user.age,
login: user.login,
password: user.password,
update_at: user.update_at,
created_at: user.created_at
});
});
})
app.get('/api/users',function(req, res) {
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
}
user.service.ts
import { Observable } from 'rxjs/Observable';
import { Http, RequestOptions, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
import { db_url } from './../../../assets/db_url';
import { User } from './../../../assets/interfaces/db.interface';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class UserService {
constructor(private _http: Http) {}
registerUser(user_data: User): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let url = "http://localhost" + db_url + "/users";
return this._http.post( url, user_data , options )
.map(data => data.json())
.catch(err => err);
}
}
Try add return operator to same places
app.get('/api/users',function(req, res) {
User.find(function(err, users) {
if (err)
return res.send(err); <<<
res.json(users);
});
});