I am using ejs, expressjs, mongoose and I am rendering templates based on ejs.
One of my landing page has it tile in url. Title is input from user, he may enter with spaces or without spaces. If he entered it with spaces I'm getting an URL like below.
The below URL is complete non SEO friendly so I want to make it plain text with hyphens
http://localhost:8080/photoapp/awesome%20baby%20srija
I want to remove % and replace with - in my URL to make it SEO friendly. how can I do that?
My ejs template:
<td> Campaign Link </td>
My route: This is my post route which is rendering particular page code. How can i achieve this with javascript tags or ejs tricks.
exports.getCampList = (req, res) => {
if (!req.user) {
return res.redirect('/login');
}
Campaign.find({userId:req.user._id}, (err, campaign) => {
if(req.user){
res.render('admin/campaign-list', {
title: 'Campaigns',
camplist : campaign
});
}
});
}
I want remove all unnecessary code and make it url friendly website
You can use slugify or use regex to replace characters and spaces with a hyphen.
function slugify_text(Text){
return Text
.replace(/[^a-zA-Z0-9]+/g, "-")
.replace(/(^\s*-)|(-\s*$)/g, '');}
You can use this to slugify the page name to an SEO friendly URL.
Related
In a Net 7 project I am setting localization in Program:
builder.Services.Configure<RequestLocalizationOptions>(x => {
x.AddSupportedCultures("pt", "en");
x.AddSupportedUICultures("pt", "en");
x.SetDefaultCulture("pt");
x.RequestCultureProviders.Clear();
x.AddInitialRequestCultureProvider(new RouteDataRequestCultureProvider { RouteDataStringKey = "culture" });
});
application.UseRequestLocalization();
I have two Razor Pages (Index and About):
Index: #page "{culture?}"
About: #page "/{culture?}/about"
I am able to access Homepage (Index) using:
/
/en
/pt
But I am only able to access About page using:
/en/about
/pt/about
When I try to access "/about" the url is not changed but the homepage is rendered.
Isn't this strange?
Shouldn't redirect to Index and change the Index Url?
Or even Redirect to "/pt/about" because PT is the default culture?
I checked the RouteDataRequestCultureProvider source and I has:
if (culture == null && uiCulture == null)
{
// No values specified for either so no match
return NullProviderCultureResult;
}
Can't I define what to do when a NullProviderCultureResult occurs?
This may not answer your question, but at least will explain why it works like this.
But I am only able to access About page using:
/en/about
/pt/about
When I try to access "/about" the url is not changed but the homepage is rendered.
That is basically because the url "/about" is matching with the route /{culture} and so it assumes that "culture=about", as a result it redirects to the index page because it matches the route:
Index: #page "{culture?}"
However, since there is no culture named "about" it renders the default culture "pt" in your case.
I'm currently looking to implement pagination within the ForgeViewer PDF Extenstion, in the documentation there's a note that 'page' in the querystring will override any value passed to load model. I wondered if this was configurable or we were able to prevent this.
// URL parameter page will override value passed to loadModel
viewer.loadModel(‘path/to/file.pdf’, { page: 1 });
This is causing us a few issues as we use 'page' for other purposes and we'll have to rework quite a bit to rename our current page querystring which we're using for paginating tables.
That's correct. If you look inside the PDF extension's code (https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/extensions/PDF/PDF.js) then you'll find that this behaviour is hardcoded unfortunately 😞
I can think of two workarounds:
a) Use a URL param other than page - e.g. sheet?
b) Overwrite the current URL so that the page number will become what you need
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
// This should change the URL content without a reload
history.pushState('', '', 'index.html?page=1');
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
You could also achieve the same like this:
viewer.loadExtension('Autodesk.PDF').then(function(ext) {
// Original URL is: http://127.0.0.1:5500/index.html?page=2
// we change it to page=1
viewer.loadModel("AutoCAD_Sample_Part1.pdf", {}, (model) => {
ext.hyperlinkTracker.changePage(1)
Hi I'm using Axios to build my first API call app , the API I'm trying to get data from is the Pokemon API database pokeapi.co. The code in my app.js document to make the API call and use the data looks like this:
app.get("/", function(req, res){
res.render("home.ejs");
});
app.get("/data", async(req, res) => {
var inputSearch = req.query.searchTerm;
axios.get('https://pokeapi.co/api/v2/pokemon/' + inputSearch) //The API
.then((body) => {
var pokeData = body.data;
res.render("data.ejs", {EJSpokeData: pokeData});
})
.catch((err) => {
res.send('Data not found', err.statusCode);
})
});`
This links to a form in an ejs document that looks like this:
<form action="/data" method="GET" id="searchForm">
<input type="text" id="searchBox" placeholder="Enter Pokemon name or ID number.." name="searchTerm">
<input type="submit" value="Submit" id="submit">
</form>
The API is called when the user enters either the Pokémon's name or its ID number into the input to be passed to Axios, my system works fine and returns the data I need, however the name can't be capitalized as the name values in the central API are all lower case so capitalizing a name will cause the system to search for a value that isn't in the API and eventually time out the app giving me the error message "localhost didn’t send any data".
This will also occur if the user spells a name wrong or enters an ID number that isn't present in the API. Also, if the user leaves the input field blank a crash occurs as my ejs document tries to process data that is not present. Is there any way to launch some kind error page if the get request doesn't return any data? Is there any way to prevent the submit request being activated if the input field is blank?
I've tried to res.render an error page in the .catch section but it doesn't see to work, can anyone help?
I don't know anything about express specifically so I can't help you with how to render things, but your API questions I can help with.
If we want to call the API with a lower case name that's easy! We don't need to care about what the user types into the input because we can convert it to lower case before calling the API:
var inputSearch = req.query.searchTerm.toLowerCase();
If we want to ignore empty strings, we can use a conditional statement. There are lots of ways to check for empty strings but the easiest is to just say if (myString) {...} because an empty string will evaluate to false while all other strings are true.
if (inputSearch) {
/* ...axios... */
} else {
res.send("Empty search term");
}
There is a shop on nuxtjs and on the /catalog page I need to make a "Load more" button. By clicking on it, products should be loaded and the url should be changed to /catalog/page_2 (?page=2 is not suitable).
If I change the url through $router.push nuxt goes to this page, but I need to change the url, but not go anywhere.
Is it possible to somehow undo the reloading but save the changes in the url?
history.pushState copes with the task, but in this case nuxt does not know that the url has changed and when clicking forward / backward in the browser nuxt does not load the goods needed for this page
Paginations logically belong to the main page so It's good to consider them in URL queries, like ?page=2.
also you can use router.replace to change queries.
this.$router.replace({
query: { ...this.$route.query, page: this.page},
})
Do it with this example
https://codesandbox.io/s/withered-darkness-9ezn9?file=/pages/index/_id.vue
Now I can change the filters, categories, and the url changes, but the page does not reload
As you don't want to change the page if you are already on the correct one, check for differences in current page URL first;
const your_query = '?page=2' // containing url params
const currPath = this.$route.fullPath; // containing current path + query params, e.g. '/catalog/?page=2'
const nextPath = `${this.$route.path}?${your_query)}`;
if (currPath !== nextPath) {
//"Abuse" router to change the current's windows url
this.$router.replace(nextPath, undefined, () => {
//If route navigation fails, e.g. due to a same-route navigation or wrong permissions in navigation-guards, handle here
return;
});
}
Alternative would be to directly pass the new query params to the router, as:
this.$router.replace({ query:
page: 2
})
Similar to this
I have the following route:
app.get('/blogpost/:link', middleware.loginCheck, blog.postBlogs);
Using req.params.link returns the link parameter.
When I ask for the req.params.link in middleware.loginCheck I receive an undefined.
It seems that req.params.link is not being passed through to the middleware because I can access it like so:
app.get('/blogpost/:link', function(req, res){console.log(req.params.link)});
Whats the problem with my middleware?
FINAL
a(href='/post/#{post.link}') #{comments} renders /post/myPostLink
{#post.link} only renders the variable substitute and does not add an extra /
a(href='/post#{post.link}') #{comments} renders '/postmyPostLink'
a(href='/post/' + post.link) #{comments} renders /post/myPostLink
So both #{post.link} or post.link work the same and req.params.link works on both calls.
UPDATE_2
I am using jade to render the web page. Inside there I have an anchor tag written as so: a(href='/post/#{post.link}) #{comments}
The achor tag works fine and directs me to the correct page. But express does not like this representation. Instead, if I change the anchor tag to a(href='/post/' + post.link) #{comments} req.params.link works fine.
UPDATE_1
req.param('link') works for this case.
There is no problem with the middleware.
But why wouldn't req.params.link work?
OK, we went back and forth in the comments a bit, but now my guess is that the problem is double slashes in your URL
a(href='/post/#{post.link}') #{comments}
That is A) missing a closing quote, but I assume that is a typo just in your question here, not in your code. and B) the real problem is that post.link includes a leading slash, so you end up with this HTML:
<a href='/post//post_link_name'>42</a>
Thus express is parsing that as an empty :link parameter. Change your jade to this:
a(href='/post#{post.link}') #{comments}
and you should get back in business.
In recent versions of express you can use router.param() as your middleware to specifically work on the req.params:
var router = express.Router();
router.param( "nickname", function (req, res, next, nickname) {
console.log( "nickname: ", nickname );
next();
});
router.get( "/user/:nickname", myController.method );
what does the signature of middleware.loginCheck look like? It needs to return a function(req, res, next)