I have an url like this: http://localhost/editblog/58a5da1df3ec9614fc9893d3
and code in pug like this:
input.form-control(type='hidden', name='id', value='')
The question is how to get the value on the url and pass it to value=''
I've known about req.params.id but it is not what could solve my issue
When you render your pug template you could send any variable as res.locals property so it will send to template:
app.get('/editblog/:id', function(req, res) {
res.render('editblog', { title: 'edit blog', id: req.params.id });
});
And now you have access to id whithin your template:
editblog.pug:
input.form-control(type='hidden', name='id', value=id)
Related
I have this code which send what the active user publish into mongodb id of the post + author + author ID + caption(what the author write), the code works perfectly but the problem that this statementcaption : req.body.caption,is keep returning null to mongodb and I really don't know why or how to solve this,
the code of publish is below :
router.post("/publish", function (req, res, next) {
// Generate a random id
User.findById(req.user.id, function (err, user) {
if (!user) {
req.flash('error', 'No account found');
return res.redirect('/login');
} else {
}
user.posts.push({
_id: guid.raw(),
author: user.userName,
authorID: user.id,
caption : req.body.caption,
comments: [],
likes: [],
createdAt: new Date(),
lastEditedAt: new Date()
});
user.save(err => {
if (err) throw err;
console.log("Post saved");
res.redirect("/");
});
});
});
the schema of caption is below :
caption :{type : String}
the ejs part is also below
<input
type="text"
id="caption"
name="caption"
class="form-control"
placeholder="enter your posts"
value="Share your thoughts!"
/>
MongoDB screen
Please some help,
Best Regards,
Your output from console.log(req.body) -- an empty body object -- proves beyond any doubt that no form fields are arriving at your route handler in your post.
It's possible you need to tell express to use a couple of middleware modules to parse the data in the bodies of POST requests. Try putting these two lines in your code somewhere before your call(s) to app.use('/', router).
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
These will make express populate the req.body object with the data from your forms. It chooses JSON or url-encoding based on the Content-Type: header.
Or it's possible your html (ejs) doesn't have your <input...> fields wrapped in your <form....> object. You can tell if this is true by looking at your POST request in the Network tab of your browser. You'll find a section called Form Data if you click on the POST request. If it's empty, your form post sent nothing. If the caption field is empty, that field wasn't wrapped in the <form ...> tag.
I need to get a full url as parameter to convert it in a qrcode. Once the url is in this format https://website.com.br/2k , I can't receive it as parameter in my node.js route
That's how I'm sending the parameter to ejs page
res.render("tutorial.ejs", { qrcode: '/qrcode/'+ link });
link is something like: http://comp.co/32
In tutorial.ejs, I render the qrcode calling qrcode route
<img src="<%= qrcode %>">
qrcode route:
routes.get('/qrcode/:url',(req,res, next) => {
const code = qr.image(req.params.url, {type: 'svg'});
res.type('svg');
code.pipe(res);
})
It's not working. I think that happening because my qrcode route is getting something like this as parameter: http://comp.co/32
when you make get request, you are basically calling
routes.get(/qrcode/http:/comp.co/32){...}
so router in the backend understands it as a route and it wont call your expected route i.e.
routes.get(/qrcode/:url){...}
Solution:
Url encode your url as and try your code again.
var link="http%3A%2F%2Fcomp.co%2F32"
res.render("tutorial.ejs", { qrcode: '/qrcode/'+ link });
<img src="<%= qrcode %>">
routes.get('/qrcode/:url',(req,res, next) => {
const code = qr.image(req.params.url, {type: 'svg'});
res.type('svg');
code.pipe(res);
})
But better way to pass parameter is using query to avoid confusion, you can do this
res.render("tutorial.ejs", { qrcode: '/qrcode?url='+ link });
routes.get('/qrcode',(req,res, next) => {
const code = qr.image(req.query.url, {type: 'svg'});
res.type('svg');
code.pipe(res);
})
Hope it solves your problem.
You can console.log(req) inside your qrcode route to see what data you can get from the request.
I am having a really hard time accessing a variable in Pug from Express.
My route looks like:
router.get('/', ensureAuthenticated, function(req, res, next) {
res.render('profile/profile', {user: req.user});
});
My template looks like:
.card
.card-body
h4.card-title Local Profile
if (user)
p.card-text
strong.pr-2 ID: !{user.userEmail}
br
br
strong.pr-2 Name:
= user
br
br
strong.pr-2 Email:
= user
br
br
strong.pr-2 Password:
span.text-muted= user
a.btn.btn-default(href="/profile/edit") Edit
p.card-text
small.text-muted Last login
= user
The user object looks like:
{UID: 5, userEmail: "rtester#testing.com", userPassword: "bd4eb56b41fc3663dfe2761ff34621a544ecfe27", userLastLogin: "2017-11-20T22:18:13.000Z", userToken: "cae45ae7e68ef8024d4ad5b56c68f263"}
If I include just user without stringifying, then I get Object object. If I stringify I can output the object, but trying to access a property in the object gives me nothing.
But if I
console.log(x.userEmail)
after
var x = !{JSON.stringify(user)}
then I get the property.
Any help would be fantastic!!
use user.userEmail instead of !{user.userEmail}
this worked fine for me,
app.get('/', function(req, res, next) {
var u = {UID: 5, userEmail: "rtester#testing.com", userPassword: "bd4eb56b41fc3663dfe2761ff34621a544ecfe27", userLastLogin: "2017-11-20T22:18:13.000Z", userToken: "cae45ae7e68ef8024d4ad5b56c68f263"}
res.render('index', { user: u });
});
,
html
head
title= user.userEmail
body
h1= user.userEmail
The issue actually had nothing to do with Pug or Express. It was with the way that Passport was setting the req.user variable after finding the user using Bookshelf.js.
There were some additional nested attributes in the object. This separate answer led me to a solution to isolate the information I needed. Cannot get properties of req.user
The way to access the information in Pug is the same as laid out in the docs.
node
app.get('/profile', function(req, res) {
res.render('profile.ejs', { authUser : req.user });
});
angular
function Ctrl($scope) {
$scope.user = authUser; // from the view
}
I need access to the authUser in the Angular code. I'm familiar with using $http.get to get data from a res.json(...), but am not sure how to do it in this scenario.
res.render is only sending the authUser to the EJS view engine, not back to the client. If you only need to display the user info then you can add something like <%= authUser.displayName %> to profile.ejs.
How do I translate the examples from the shrinkroute README file:
// or views...
User profile
User profile
for use in jade templates?
For example, something like
a(href="#{ url( "user", { id: 1 }) }") User profile
Thanks in advance.
First of all, ensure that you're using the shrinkroute middleware:
app.use( shrinkr.middleware );
It'll automatically provide you the following helpers:
req.buildUrl and res.locals.url - builds paths for a route. The same as using shrinkr.url().
req.buildFullUrl and res.locals.fullUrl - builds full URLs for a route. The same as using shrinkr.fullUrl().
In Jade, you simply have to use the following:
a(href=url( "user", { id: 1 } )) My Username
a(href=fullUrl( "user", { id: 1 } )) My Username
Rendered output:
My Username
My Username
The above output will depend on the routes you have named in your shrinkroute instance.
Disclaimer: I'm the creator of Shrinkroute.
here's a general solution for calling a function from within a template; see #gustavohenke 's answer for a specific solution for how to use shrinkroute's built-in locals.buildFullUrl function within a jade template
// node.js
var url = require('url');
// Set up locals.shrinkUrl for every request
app.all('*', function(req, res, next){
res.locals.shrinkUrl = function(path, queryObject){
var out = url.format({
pathname: path,
query: queryObject,
});
return out;
};
next();
});
// template.jade
a(href=locals.shrinkUrl("user", {id: 1}) ) User profile
// rendered
<a href='/user?id=1'>User profile</a>