How to dynamically define nested routes in express/node.js - html

I'm pretty new to the express/nodejs and would like to apply a route such that routes are dynamically adapted based on the article name.
The articles are saved within articles.js consisting of
const articles = [{
title: 'article1',
link: 'article2',
creator: 'Anna',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True'
},
{
title: 'article2',
link: 'article2',
creator: 'Sascha',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True'
},
{
title: 'article3',
link: 'article3',
creator: 'Anna',
createdAt: '17/10/2021',
description: 'Test description',
publish: 'True'
}]
exports.articles = articles;
In a seperate file I'm defining my routes in index.js:
const express = require('express')
const router = express.Router()
//load arcticles
const Articles = require('../articles/articles');
// ----Routing----
router.get("/", async (req, res) => {
const articles = await Articles.articles.filter(all => all.publish ==='True')
res.render("index", {articles: articles});
});
router.get("/route1", async (req, res) => {
const articles = await Object.values(Articles.articles).filter(all => all.publish ==='True');
res.render("route1", {articles: articles});
});
router.get("/route1/:link", async (req, res, next) => {
const articles = await Object.values(Articles.articles).filter(all => all.publish ==='True');
var name = req.params.link;
return res.json({ message: 'Users Show', Articles: name});
});
module.exports = router
However, when trying to access these via my HTML file, this doesnt seem to work
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Clean Blog - Start Bootstrap Theme</title>
<link href="../css/styles.css" rel="stylesheet" />
</head>
<body>
<!-- Main Content-->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<!-- Post preview-->
<div class="post-preview">
<% articles.forEach(article => { %>
<h2 class="post-title" style="margin-bottom: -1.41rem"><%= article.title %></h2>
</div>
</div>
</div>
</div>
<!-- Footer-->
<footer class="border-top">
</footer>
<!-- Bootstrap core JS-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<script src="js/scripts.js"></script>
</body>
</html>
I suppose that within the HTML file the routes cannot be catched properly, however I cannot tell how why this is the case.

Related

Open Graph not displaying properly on Twitter [duplicate]

I am trying to fetch content from an API and show it in a page. It's working fine but when I am trying to view page source code it's not showing those content that I am getting from API. I am using Next.js for this project and the code that I have used is following. Is there anyone who can help help me to solve this issue?
import React, { Fragment, useEffect, useState } from 'react'
import { API_BASE_URL } from '../Config/Settings'
import SideBar from '../Layouts/SideBar'
import Link from "next/link"
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import axios from 'axios'
export const CmsPage = (props) => {
const [PageHtmlContent, setPageContent] = useState('');
const [PageTitle, setPageTitle] = useState('');
const [PageDescription, setPageDescription] = useState('');
const [SeoKeyword,setSeoKeyword]=useState('');
useEffect( async() => {
let body = {pageTypeCode:props.pageType,pageName:props.pageName};
const config = {
headers: {
'x-auth-token':"rpsite-public-token"
}
}
try {
const res= await axios.post(API_BASE_URL+'/api/cms/page',body,config);
// alert(res.data.content);
setPageContent(res.data.content);
setPageTitle(res.data.seoTitle);
setPageDescription(res.data.seoDescription);
setSeoKeyword(res.data.seoKeyword);
}
catch(err) {
setPageContent('<b>Something went wrong!</b>');
}
},[props]);
return (
<section class="inner-body-section">
<Head>
<title>{PageTitle}</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta name="keywords" content={SeoKeyword} />
<meta name="description" content={PageDescription}/>
</Head>
<div class="container">
<div class="row">
<div class="col-md-3">
<SideBar/>
</div>
<div class="col-md-9">
<div className="inner-body-content">
<div id="contentBlock" className="page-content" dangerouslySetInnerHTML={{__html:PageHtmlContent}}></div>
</div>
</div>
</div>
</div>
</section>
)
}
export default CmsPage;
What you get when looking at View Page Source is the HTML returned by the server.
Because you're making the request and populating the data inside a useEffect this will only occur on the client, thus the data won't be visible in the page's source.
If you want the data to be populated on the server you may want to have a look at getStaticProps or getServerSideProps instead.
Here's an example of how you can use getStaticProps to populate the data on the server-side (a similar approach could be used with getServerSideProps).
export async function getStaticProps(context) {
const res = await axios.post(`${API_BASE_URL}/api/cms/page`);
// Assuming `res.data` format: { content, seoTitle, seoDescription, seoKeyword }
return {
props: res.data
};
}
const CmsPage = ({ content, seoTitle, seoDescription, seoKeyword }) => {
return (
<>
<Head>
<title>{seoTitle}</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta name="keywords" content={seoKeyword} />
<meta name="description" content={seoDescription}/>
</Head>
<section class="inner-body-section">
<div class="container">
<div class="row">
<div class="col-md-3">
<SideBar/>
</div>
<div class="col-md-9">
<div className="inner-body-content">
<div id="contentBlock" className="page-content" dangerouslySetInnerHTML={{__html: content}}></div>
</div>
</div>
</div>
</div>
</section>
</>
)
}
export default CmsPage;

jQuery of droplist not working in layout ASP.NET MVC 5

I added an external theme to my project, and I wrote a script to list data in dropdownlist that works on another page (unrelated to external theme), but doesn't work in the Layout theme page.
HomeController
Notice: City District and Neighborhood get partial view is working.
I didn't copy the code because it's too much.
public PartialViewResult PartialFilter()
{
ViewBag.countrylist = new SelectList(CountryGet(), "CountryId", "CountryName");
ViewBag.statuslist = new SelectList(statusGet(), "StatusId", "StatusName");
return PartialView();
}
public List<Country> CountryGet()
{
List<Country> countries = db.Countries.ToList();
return countries;
}
public ActionResult CityGet(int CountryId)
{
List<City> cities = db.Cities.Where(x => x.CountryId == CountryId).ToList();
ViewBag.cityListesi = new SelectList(cities, "CityId", "CityName");
return PartialView("CityPartial");
}
public ActionResult DistrictGet(int CityId)
{
List<District> districtlist = db.Districts.Where(x => x.CityId == CityId).ToList();
ViewBag.districtListesi = new SelectList(districtlist, "DistrictId", "DistrictName");
return PartialView("DistrictPartial");
}
public ActionResult NgbhdGet(int districtid)
{
List<Neighborhood> neighborhoodlist = db.Neighborhoods.Where(x => x.DistrictId == districtid).ToList();
ViewBag.nghbdlistesi = new SelectList(neighborhoodlist, "NeighborhoodId", "NeighborhoodName");
return PartialView("NgbhdPartial");
}
PartialFilter.cshtml
<div class="col-12 col-lg-10">
<div class="row">
<div class="col-12 col-md-6 col-lg-3">
#if (ViewBag.countrylist != null)
{
#Html.DropDownListFor(m => m.CountryId, ViewBag.countrylist as SelectList, "Select Country", new { #class = "form-control" })
}
</div>
<div class="col-12 col-md-6 col-lg-3">
#Html.DropDownListFor(m => m.CityId, new SelectList(""), "First Choice Country Name", new { #class = "form-control" })
</div>
<div class="col-12 col-md-6 col-lg-3">
#Html.DropDownListFor(m => m.DistrictId, new SelectList(""), "First Choice City Name", new { #class = "form-control" })
</div>
<div class="col-12 col-md-6 col-lg-3">
#Html.DropDownListFor(m => m.NeighborhoodId, new SelectList(""), "First Choice district Name", new { #class = "form-control" })
</div>
</div>
</div>
The dropdown script in PartialFilter the scripts working very well in another layout page
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
var cid = $(this).val();
debugger
$.ajax({
type: "Post",
url: "/Home/CityGet?CountryId=" + cid,
contentType: "html",
success: function (response) {
debugger
$("#CityId").empty();
$("#CityId").append(response);
}
})
})
})</script>
<script>
$(document).ready(function () {
$("#CityId").change(function () {
var sid = $(this).val();
debugger
$.ajax({
type: "Post",
url: "/Home/DistrictGet?CityId=" + sid,
contentType: "html",
success: function (response) {
debugger
$("#DistrictId").empty();
$("#DistrictId").append(response);
}
})
})
})</script>
<script>
$(document).ready(function () {
$("#DistrictId").change(function () {
var districtid = $(this).val();
debugger
$.ajax({
type: "Post",
url: "/Home/NgbhdGet?DistrictId=" + districtid,
contentType: "html",
success: function (response) {
debugger
$("#NeighborhoodId").empty();
$("#NeighborhoodId").append(response);
}
})
})
})</script>
The External Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Favicon -->
<link rel="icon" href="~/Content/img/core-img/favicon.png">
<!-- Stylesheet -->
<link rel="stylesheet" href="~/Content/style.css">
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/MyStyle.css" rel="stylesheet" />
</head>
<body>
#Html.Action("PartialFilte" ,"Home")
<!-- **** All JS Files ***** -->
<!-- jQuery 2.2.4 -->
<script src="/Content/js/jquery.min.js"></script>
<!-- Popper -->
<script src="/Content/js/popper.min.js"></script>
<!-- Bootstrap -->
<script src="/Content/js/bootstrap.min.js"></script>
<!-- All Plugins -->
<script src="/Content/js/bbunbles.bundle.js"></script>
<!-- Active -->
<script src="/Content/js/default-assets/active.js"></script>
</body>
</html>
DevTools failed ....
I fixed it according to this:
[enter link description here][2]
enter link description here
but the data doesn't show
I notice that you have ~ on few lines that are not compiled on code behind, and because your JavaScript is not working - first remove that symbol from all lines like:
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
Beside that open the browser tools to check if every javascript library is correct loaded.

Get Json values with Axios

I'm trying to get all "Title", "Year" and "imdbID" from this link.
I'm using Vuejs and Axios to do so. But I'm not sure how it's done ?
Here's my code :
<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8>
<meta http-equiv="X-UA-COMPATIBLE" content="IE=edge">
<title>Web Project 2018</title>
<link rel="stylesheet" href="">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h2>Liste of films</h2>
<ul>
<li v-for="film in films">{{ film.Title }}, {{ film.Year }}, {{ film.imdbID }}</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data : {
films: [],
errors: []
},
created() {
axios.get('http://www.omdbapi.com/?apikey=xxxxx&s=iron%20man')
.then(function(response) {
this.films = response.data;
})
.catch(function(error) {
this.errors.push(error);
});
}
})
</script>
</body>
</html>
With this, I only get a page with {{ film.Title }}, {{ film.Year }}, {{ film.imdbID }}
I'm sure it's simple but I can't figure it out... Any help please ?
Worked with arrows :
axios.get('http://www.omdbapi.com/?apikey=xxxx&s=iron%20man')
.then(response => {
this.films = response.data.Search;
})
.catch(error => {
this.errors.push(error);
});

ExpressJS Fetching value from nested JSON Object

I am using ExpressJS..When trying to fetch value from the req.body, in the console.log(req.body[ndx])(it prints { " c o..... like this as single character)
for (var ndx in req.body){
console.log(req.body[ndx]);
}
My req.body has the below nested JSON Object: How to extract count?
req.body["count"] outputs undefined
{"count":1,"totalCount":38,"node":[{"categories":[],"foreignSource":null,"foreignId":null,"label":"172.20.96.20","assetRecord":{"description":null,"operatingSystem":null,"category":"Unspecified","password":null,"id":2655,"username":null,"vmwareManagedEntityType":null,"vmwareManagementServer":null,"numpowersupplies":null,"hdd6":null,"hdd5":null,"hdd4":null,"hdd3":null,"hdd2":null,"hdd1":null,"storagectrl":null,"thresholdCategory":null,"enable":null,"connection":null,"autoenable":null,"cpu":null,"ram":null,"snmpcommunity":null,"rackunitheight":null,"admin":null,"additionalhardware":null,"inputpower":null,"vmwareManagedObjectId":null,"vmwareState":null,"vmwareTopologyInfo":null,"circuitId":null,"assetNumber":null,"rack":null,"slot":null,"region":null,"division":null,"department":null,"building":null,"floor":null,"room":null,"vendorPhone":null,"manufacturer":null,"vendor":null,"modelNumber":null,"supportPhone":null,"maintcontract":null,"maintContractNumber":null,"maintContractExpiration":null,"displayCategory":null,"notifyCategory":null,"pollerCategory":null,"vendorFax":null,"vendorAssetNumber":null,"lastModifiedBy":"","lastModifiedDate":1433277477504,"dateInstalled":null,"lease":null,"leaseExpires":null,"managedObjectInstance":null,"managedObjectType":null,"serialNumber":null,"port":null,"comment":null},"lastCapsdPoll":1433277477793,"createTime":1433277477504,"labelSource":"A","type":"A","id":"10"}]}
My Code:
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use('/index', function(req, res, next){
var getReq = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
jsnArry += chunk;
});
res.on('end', function (chunk) {
req.body = jsnArry;
for (var ndx in req.body){
console.log(req.body[ndx]);
}
next();
});
}).end();
});
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use('/index', urlencodedParser, function(req, res, next){
res.send(req.body);
next();
});
console.log(JSON.parse(req.body)) o/p below ones
{ count: 1,
totalCount: 38,
node:
[ { categories: [],
foreignSource: null,
foreignId: null,
label: '172.20.96.20',
assetRecord: [Object],
lastCapsdPoll: 1433277477793,
createTime: 1433277477504,
labelSource: 'A',
type: 'A',
id: '10' } ] }
var options = {
host: host,
method: 'GET',
headers: {
'Accept' : 'application/json'
}
};
res.json(info["totalCount"]);
res.sendFile(path.join(_dirname, '/html', 'index.html'));
//Only shows the res.json value not the html page
Below is my html file:
<!DOCTYPE html>
<html data-ng-app="shopStore">
<head>
<meta charset="ISO-8859-1">
<title>Simple Angular Testing</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"></link>
<link rel="stylesheet" type="text/css" href="css/main.css"></link>
</head>
<body>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/d3.min.js"></script>
<script type="text/javascript" src="js/product.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<div data-ng-controller="scopeCtrl">
<div data-ng-repeat="x in newRec">
<p>I am product seller {{x.Name}} in {{x.City}} # {{x.Country}}</p>
</div>
{{newRec[0].Name}}
</div>
<div data-ng-controller="nmsCtrl">
<p>Data to display</p>
<!-- <div data-ng-repeat="jsn in jsnData">
<p>I am product seller {{jsn.count}} displayed out of {{jsn.totalCount}}</p>
</div> -->
</div>
<div data-ng-controller="Store-Controller as store">
<div data-ng-repeat="product in store.products">
<div data-ng-hide='product.cantPur'>
<h6>Product:::{{product.item}}</h6>
<h6>Dollar Price:::{{product.dollar | currency}}</h6>
<h6>Description::::{{product.desc}}</h6>
<h6>{{review.stars}}</h6>
<button data-ng-show='product.canAdd'>Add to Cart</button>
<product-panel></product-panel>
</div>
</div>
</div>
</body>
</html>
Do you include body-parsing middleware? body-parser support JSON parsing.
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
bodyParser.json also expect to receive payload in application/json content type. Example using jQuery ajax:
.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You probably need to convert the req.body into json using
bar myRes= JSON.parse(req.body);
console.log(myRes.count);
This should be done for you automatically. How is your bodyParser middleware set uup?
It should be set up as in the next post.

Cannot get separate views to appear in index.html, and controller is also not working

I'm just starting out with Angular and most of programming in general. I'm trying to make a separate view1.html file appear on my index.html page but it won't, so I'm assuming it's a routing problem. I tried pasting the view1.html content in the body of my index.html to test it and it wasn't showing the controller content either. I'm sure they're simple mistakes but I can't find them. view.html is in a separate folder called views. I only have the javascript in the index.html page for convenience.
index.html
<!DOCTYPE html>
<html lang="en" ng-app='demoApp'>
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<body>
<div>
<div ng-view></div>
</div>
<script>
// create module called "demoApp" under the variable name "demoApp"
var demoApp = angular.module('demoApp', []);
// ROUTING
demoApp.config(function ($routeProvider) {
$routeProvider
.when ('/',
{
controller: 'SimpleController',
templateUrl: 'views/view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'views/view2.html'
})
.otherwise({ redirectTo: '/' });
});
// CONTROLLERS
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [
{ name: 'Caleb', city: 'Indianapolis' },
{ name: 'Samantha', city: 'Zionsville' },
{ name: 'Tim', city: 'Palo Alto' }
];
$scope.addCustomer = function () {
$scope.customers.push(
{
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
}
</script>
</body>
</html>
view1.html
<h2>View 1</h2>
Name:
<input type="text" ng-model="name" />
<ul>
<li ng-repeat="cust in customers"></li>
</ul>
Customer Name:
<input type="text" ng-model="newCustomer.name" />
<br>Customer City:
<input type="text" ng-model="newCustomer.city" />
<br>
<button ng-click="addCustomer()">Add Customer</button>
View 2
</div>
You need to include the script for angular's router.
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.min.js"></script>
Also, looks like you're missing a closing </head> tag.
Here's a working version of your HTML file:
<!DOCTYPE html>
<html lang="en" ng-app='demoApp'>
<head>
<meta charset="UTF-8">
<title>First Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.js"></script>
</head>
<body>
<div>
<div ng-view></div>
</div>
<script>
// create module called "demoApp" under the variable name "demoApp"
var demoApp = angular.module('demoApp', ['ngRoute']);
// ROUTING
demoApp.config(function ($routeProvider) {
$routeProvider
.when ('/',
{
controller: 'SimpleController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'view2.html'
})
.otherwise({ redirectTo: '/' });
});
// CONTROLLERS
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [
{ name: 'Caleb', city: 'Indianapolis' },
{ name: 'Samantha', city: 'Zionsville' },
{ name: 'Tim', city: 'Palo Alto' }
];
$scope.newCustomer = { name: "", city: ""};
$scope.addCustomer = function () {
$scope.customers.push(
{
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
};
});
</script>
</body>
</html>