I've got a task in JavaScript but I don`t know anything about it. I found a video which helped to solve my problem but now I must create a form which check all results. In postman I entered token and pass.
const express = require('express');
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const cod = 123
const secret = speakeasy.generateSecret();
console.log(secret);
app.get('/', (req, res) => {
res.send('hello');
})
app.get('/twofactorsetup', (req, res) => {
QRCode.toDataURL(secret.otpauth_url, (err, data_url) => {
res.send(
`<h1>setup authenticator</h1>
<img src=${data_url} >
<br>Manually: ${secret.base32}`
);
})
})
app.post('/verify', (req, res) => {
token = req.body.userToken;
const pass = req.body.pass;
token = token - cod;
console.log('first');
console.log(token);
token = token + pass
console.log('sec');
console.log(token);
const verfied = speakeasy.totp.verify({ secret: secret.base32, encoding: 'base32', token: token });
res.json({ success: verfied });
})
app.listen(3000, () => {
console.log('Server started ISZZI');
});
What should I do? Any videos or tutorials
Thank you!
Related
I want to send data for products from my post request
router.post("/addProduct",(req, res) => {
const {addName, addDescription, addPrice, addImg} = req.body;
console.log(`${addName} added, the price is ${addPrice}`)
})
into the get request
router.get("/addProduct",(req, res) => {
//console.log(`getting ${addName}, and the price is ${addPrice}`)
console.log(`getting the response ${addName}`)
})
i want to send the const {addName, addDescription, addPrice, addImg} = req.body; into the get request, but I haven't found a lot of info on how to do that
You can, but it's against the convention.
const express = require("express");
const app = express();
const router = express.Router();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(router);
router.get("/addProduct", (req, res) => {
const { addName } = req.body;
console.log(`getting the response ${addName}`);
return res.json(addName);
});
app.listen(3000, (req, res) => {
console.log("listening...");
});
I am able to run a test in Postman, but for some reason I am not passing my hashed password into the DB correctly.
const express = require("express");
// const helmet = require("helmet");
const { User } = require("./db/models");
const bcrypt = require("bcryptjs");
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync('bacon', 8);
const port = 4000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
// app.use(helmet());
app.get("/", (req, res) => {
res.send("Hello World!");
});
Here is where i suspect the issue is. I am passing the name, email, and password in. I am trying to figure out how to get the hash to pass into the DB as the password.
app.post("/register", async (req, res) => {
const user = await User.create({name:req.body.name, email:req.body.email, password:req.body.password});
bcrypt.genSalt().then(salt => {
bcrypt.hash("password", salt).then(hash =>{
console.log(hash);
});
})
console.log(req.body.name)
res.json(user);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Since you are in an async function you can use await to get the values before creating the User object
app.post("/register", async (req, res) => {
const salt = await bcrypt.genSalt();
const hashed_password = await bcrypt.hash(req.body.password,salt);
const user = await User.create({name:req.body.name, email:req.body.email, password:hased_password});
console.log(req.body.name)
res.json(user);
});
const hashedPwd = await bcrypt.genSalt().then(salt => {
return bcrypt.hash("password", salt);
})
is that you want?
You have to save the user collection. That is, after hashing the password, the user's password must be changed.
user.password = hash;
user.save()
I'm writing a code for creating a group within a website. And I'm using MongoDB as my database, but as a beginner, it's hard for me to understand the API that they provide. So basically, I'm having issues with connecting the backend to the frontend when I'm trying to create a group for my website. This is the backend code for create_group
router.post('/create_group', (req, res) => {
try {
const newGroup = Group.create(req.body);
res.status(201).json({
data: {
Groups:
newGroup
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
//res.json(database.groups[database.groups.length-1]);
As you can see, I want to write a code that's appropriate for MongoDB that looks like the portion that I commented out. I want to return the object that I just saved so I can display that information in when I change the route. The frontend code looks like this:
onSubmitCreate = () => {
fetch('http://localhost:3000/groups/create_group', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
members: 1,
likes: 0
})
})
.then(response => response.json())
.then(group => {
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);
}
});
}
In the frontend, as I make a request to post the information to the database, I want to read the response and work with that information. But when I console.log the group variable, I just get an empty object as a response and I don't know how to make it return the information that the user typed in. And in case you want to see what onCreateGroup fucntion looks like, here it is.
const onCreateGroup = (group) => {
setGroupInfo({
name: group.name,
description: group.description,
likes: 0,
members: 1
});
setRoute('group_page');
}
Please help me! Thank you in advance!
Edit: I was requested to post js file where I import express so I'm posting it here
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://teamboogle:wMKsYJNhTfL89k9#cluster0.nhcrc.mongodb.net/TalkWithMe?retryWrites=true&w=majority", { useNewUrlParser: true });
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const profileRouter = require('./routes/profile');
const postsRouter = require('./routes/posts');
const groupsRouter = require('./routes/groups');
const signinRouter = require('./routes/signin');
const registerRouter = require('./routes/signin');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/profile', profileRouter);
app.use('/posts', postsRouter);
app.use('/groups', groupsRouter);
app.use('/signin', signinRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function(){
console.log('Connection Secured');
})
module.exports = app;
You are not saving the object in MongoDB properly, and you also need to return the object that you saved in Group collection as well.
Also, since you are returning data.Groups.group, you need to read that in the response as well
Please try this:
router.post('/create_group', async (req, res) => {
try {
const newGroup = new Group(req.body);
let group = await newGroup.save()
res.status(201).json({
data: {
Groups:
group//return the saved object
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
}
In frontend code
onSubmitCreate = () => {
fetch(...)
.then(response => response.json())
.then(data => {
// read data.Groups.group from response
let group = data.Groups.group
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);
}
});
}
I am trying to generate a jwt token and print it out by calling res.json() after the user has been authenticated, the problem is that I get the following error:
Cannot set headers after they are sent to the client
I tried solving the issue by using async and await but it still gives me the error. How can I res.json my token successfully?
Here is my node.js server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const BASE_URL = process.env.BASE_URL;
const PORT = process.env.PORT || 1337;
const jwt = require('jsonwebtoken');
let Post = require('./models/post.model.js');
app.use(cors());
app.use("/assets", express.static(__dirname + "/assets"));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(BASE_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
app.set('view-engine', 'ejs');
app.get('/', (req, res) => {
res.render('index.ejs');
});
app.post('/', (req, res) => {
let username = req.body.username;
let password = req.body.password;
if (username !== process.env.USER_NAME && password !== process.env.USER_PASSWORD) {
res.json('Invalid credentials');
} else {
const token = jwt.sign({
username: username,
password: password
}, process.env.SECRET_KEY, {
expiresIn: '1h'
});
res.redirect('/dashboard');
res.json(token);
}
});
app.get('/dashboard', (req, res) => {
res.render('dashboard.ejs');
});
app.get('/dashboard/createPost', (req, res) => {
res.render('post.ejs');
});
app.post('/dashboard/createPost', async (req, res) => {
let collection = connection.collection(process.env.POSTS_WITH_TAGS);
res.setHeader('Content-Type', 'application/json');
let post = new Post(req.body);
collection.insertOne(post)
.then(post => {
res.redirect('/dashboard')
})
.catch(err => {
res.status(400).send(err);
});
});
app.listen(PORT);
You are calling res.redirect('/dashboard'); before the res.json(token);, you can't send a response twice that's why it's giving you the Cannot set headers after they are sent error.
What you can do instead is sending the token as a query via the redirect like this:
res.redirect(`/dashboard?token=${token}`);
Then you can get the token value from the front-end app by checking the query value.
Although this is not a very safe method
I am trying to post to my cosmosDB using Angular. I can GET just fine, but POST returns with a 404 error in Postman. I am new to routes and APIs so I am a little lost on what is causing the issue.
Here is my index.js
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'dist/checkin')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('dist/checkin/index.html', {root});
});
app.listen(port, () => console.log(`API running on localhost:${port}`));
My routes.js
const contactService = require('./contact.service');
const router = express.Router();
router.get('/contacts', (req, res) => {
contactService.getContacts(req, res);
});
router.post('/contact/', (req, res) => {
contactService.postContact(req, res);
});
module.exports=router;
My contact.service.js which contains all of my operations (Just GET and POST right now)
const ReadPreference = require('mongodb').ReadPreference;
require('./mongo').connect();
function getContacts(req, res) {
const docquery = Contact.find({}).read(ReadPreference.NEAREST);
docquery
.exec()
.then(contacts => {
res.status(200).json(contacts);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postContact(req, res) {
const originalContact = { uid: req.body.uid, name: req.body.name, description: req.body.description };
const contact = new Contact(originalContact);
contact.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(contact);
console.log('Contact created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
module.exports = {
getContacts,
postContact
};
Input is obtained through an HTML forum which is picked up and sent through
return this.http.post<Contact>(`${api}/contact/`, contact);
}