I would like to get the data from session variable (req.user.username) then use it for posting. I'm using passportjs as authentication. I'm using router. Here is my code:
router.use('/login', passport.authenticate("local-register", async (err, user, info) => {
if (err) {
return next('Error');
}
if (!user) {
return next('Error');
}
req.user = user;
return req.login(user, (error: Error) => {
if (error) {
return next('Error');
}
return req.session.save((erro: Error) => {
if (erro) {
return next('Error');
}
return next();
});
});
})(req, res, next);)
router.get('/', async (req, res) => {
console.log(req.user.username) // working just fine
});
router.post('/upload', async (req, res) => {
const uploaderName = req.user.username // I'm getting undefined
const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])
console.log(uploaderName);
})
So I finally found the answer to the question. For those who will encounter the problem in the future. You just add the session middleware AGAIN on the top of the routes. If your routes are separated to the main server file.
/src/routes/routes.ts -> add again the middleware on top.
const app = router();
app.use(sessions) // -> right here you need to add the middleware again to //access the req.user session variable
app.get('/', async (req, res) => {
console.log(req.user.username) // working just fine
});
app.post('/upload', async (req, res) => {
const uploaderName = req.user.username // I'm getting undefined
const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])
console.log(uploaderName);
})
Related
UPDATE: I it checks for /:slug even if i go to a different route, i think thats causing the problem.
I'm trying to create a URL Shortener with Nodejs, Expressjs, MongoDB and EJS.
Even though my application is working perfectly, I keep getting this error in terminal:
My routes :
const express = require("express");
const URLs = require("../models/urls");
const { findById, find } = require("../models/urls");
const router = express.Router();
router.get("/", (req, res) => {
res.render("index", { shortUrl: new URLs() });
});
router.post("/redirect", (req, res) => {
let url = req.body.url;
let slug = req.body.slug;
let shortenUrl = new URLs({
url: url,
slug: slug,
});
shortenUrl.save();
res.render("shortenUrl", { shortenUrl });
});
router.get("/about", (req, res) => {
res.render("about");
});
router.get("/contact", (req, res) => {
res.render("contact");
});
router.get("/all", async (req, res) => {
try {
var shortUrls = await URLs.find({});
res.render("all", { shortUrls });
} catch (error) {
console.log(error);
}
});
//:TODO
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
});
module.exports = router;
I didn't get this error until I made API for the app (in separate routes file).
Also in my server I'm using:
app.use(bodyParser.urlencoded({ extended: false }));
and using:
app.use(express.json());
doesn't help either.
Any help would be appreciated, Thank you c:
I added an if statement to the route and that solved the problem, thanks to #Pukka c:
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
if (shortUrl) {
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
}
i am new to node.js and want to create api for getting data and update that data on frontend,please give me solution for this,i am getting data from this code but unable to update data.I am using react js for frontend.
var express = require("express");
var app = express();
var oracledb = require('oracledb');
var dbconfig= require('./dbconfig')
(async function () {
let connection
try {
connection = await oracledb.getConnection({
user: 'dbconfig.user',
password: 'dbconfig.password',
connectString: 'dbconfig.connectstring'
});
var result = await connection.execute('select * from
PROPERTY.app_booklet_challan_detail', []);
console.log("Successfully connected to Oracle!")
console.log(result)
} catch (err) {
console.log("Error: ", err);
} finally {
if (connection) {
try {
await connection.close()
} catch (err) {
console.log("Error when executing the database connection: ", err);
}
}
}
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
next();
});
app.get('/list', (req, res, next) => {
res.send(result);
next()
});
app.put('/list/update', (req, res, next) => {
let STATUS=res.data
connection.execute('UPDATE PROPERTY.app_booklet_challan_detail SET STATUS= ? WHERE
BOOKLETID= ? ', [STATUS])
res.send(STATUS)
next()
})
app.listen(3001, function () {
console.log("Started on PORT 3001");
})
})()
Your question is a little broad to answer with code, but I've written an entire series on this topic: https://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/
Note there are links to a GitHub repo with the code from each module.
Once you finish with the series you should be able to take things in the direction that makes the most sense for your project.
In express.js, if I have this route in my server side
router.get('/ad/:id', (req, res) => {
const { id } = req.params
Ad.getAd(id, (err, resp) => {
if(err){
return handleError('Failed to load an ad', res)
}
res.json({
success: true,
result: resp
})
})
})
and it worked fine I want to load a detail ad like example.com/ad/123 where id is 123. But I can't do example.com/ad/create anymore, any way to check the type of the param?
You can create separate route for it. Place before /ad/:id route, because it's catching all requests like /ad/*.
router.get('/ad/create', (req, res) => { /* some work */ })
router.get('/ad/:id', (req, res) => { /* some work */ })
Since you mentioned you are building a SPA, you must redirect all GET requests to react-router:
app.get("*", function (req, res) {
res.sendFile(__dirname + "/path/to/index.html")
})
Also you can prepend api to all back-end endpoints to prevent ambiguity.
router.get('/api/ad/create', (req, res) => { /* some work */ })
router.get('/api/ad/:id', (req, res) => { /* some work */ })
router.get('/ad/:id', (req, res,next) => {
const { id } = req.params
if(! parseInt(id,10)){
return next();//skip this route if not a number
}
//its a number
});
I'm developing a module which I'm using for passport authentication with ExpressJS, and I came up with this solution to gather all the passports methods I'm using:
// passport-controller-js
exports.signup = (passport) => (req, res, next) => {
// Authenticate methods ================
passport.authenticate('local-signup', function(err, user, info) {
if (err) {
return next(err); // will generate a 500 error
}
// Saving user...
return res.send({ success : true, message : 'signup succeeded' });
})(req, res, next);
};
exports.signin = (passport) => (req, res, next) => {
passport.authenticate('local-login', function(err, user, token, info) {
if (err) {
return next(err); // will generate a 500 error
}
req.login(user, loginErr => {
if (loginErr) {
return next(loginErr);
}
return res.send({ success : true, message : 'signin succeeded' });
});
})(req, res, next);
};
But since this module will increase adding more strategies I'm thinking if there is a way to put all of them inside a module.exports like:
module.exports = (passport) => {
function signin(req, res, next) {
passport.authenticate('local-login', function(err, user, token, info) {
if (err) {
return next(err); // will generate a 500 error
}
req.login(user, loginErr => {
if (loginErr) {
return next(loginErr);
}
return res.send({ success : true, message : 'signin succeeded' });
});
})(req, res, next);
};
I know that dosn't work Im just wondering if there is a possible solution like that so when I need to require those methods on my router file for example I can do this:
// auth.js (passport is passed from index.js)
const passportController = require('../controllers/passport-controller')(passport);
// Process the signup form
router.post('/signup', passportController.signup);
router.post('/signin', passportController.signin);
Instead of:
// auth.js (passport is passed from index.js)
const passportController = require('../controllers/passport-controller');
// Process the signup form
router.post('/signup', passportController.signup(passport));
router.post('/signin', passportController.signin(passport));
As you can see is just matter of looking for the most legible way to code and keep it simpler as possible.
Any help would be appreaciated, thank you very much.
Sounds like you want to make a module that exports a single function which returns an object. The syntax for that is
module.exports = passport => ({
signup(req, res, next) {
…
},
signin(req, res, next) {
…
}
});
I'm writing some rendering-code for an Express app, I wish to catch errors and then output them in the function render, but I'm not sure how I'm going to move them from one method to the other.
app.get('/user/makeRider', auth,
(req, res, next) => {
req.user.user.makeRider(req.query)
.catch(error)
.then(render(req, res));
}
);
var render = (req, res) => {
var response = {
params: req.query,
user: req.user.fulluser
};
res.json(response);
},
error = (reason) => {
reason.errors.forEach((error) =>{
console.log(error);
});
return;
};
You can use error function as your last midleware in the chain and simply pass the request to the next chain:
var render = (req, res) => {
var response = {
params: req.query,
user: req.user.fulluser
};
res.json(response);
}
app.get('/user/makeRider', auth,
(req, res, next) => {
req.user.user.makeRider(req.query)
.catch(next)
.then(render(req, res));
}
);
app.use((reason, req, res, next) => {
res.send(reason.errors);
// or you can send them as json: res.status(404).json({errors: reason.errors})
});
Beware of hoisting issue in your code, the variable declarations are hoisted to the top, but not their assignments, error and render function may appear as undefined when accessed from your route.
A quick, but maybe not the most elegant solution would be to add errors as a parameter to your render function, then you could do something like this:
app.get('/user/makeRider', auth,
(req, res, next) => {
req.user.user.makeRider(req.query)
.catch((reason)=>{
render(req, res, reason.errors)
})
.then(render(req, res));
}
);
var render = (req, res, errs) => {
var response = {
params: req.query,
user: req.user.fulluser
};
res.json(response);
};