Если / Else Bootstrap Pagnation Rule работает только с корневым URL (Express JS / Bootstrap) - PullRequest
0 голосов
/ 30 сентября 2018

Проблема

Этот код отлично работает при посещении страницы 1 (первая страница) и страницы 574 (последняя страница), он блокирует кнопки «Предыдущая» и «Следующая» для отображения начала / конца нумерации страниц.

Однако, когда я сортирую в пригороде, URL для маршрута не устанавливается на localhost: 3000 / suburb / x (x - номер страницы), а вместо этого просто устанавливается на пригород / xдля следующей и предыдущей кнопок на нумерации пригородов.

Как я могу гарантировать, что эта нумерация страниц работает в пригороде?

Я знаю, что это может быть связано с неправильной настройкой моих маршрутов... Ниже приведен код pug для моей страницы Bootstrap и моего кода App.JS.

JADE (PUG) - index.pug

    nav(aria-label='Page navigation example')#pagination
        ul.pagination
            if currentPage == 1
                li.page-item.disabled
                    a.page-link(href='/' tabindex='-1') Previous

            else
                li.page-item
                    if suburb == null
                        a.page-link(href='/' + (currentPage - 1) tabindex='-1') Previous
                    else
                        a.page-link(href='/' + suburb + '/' + (currentPage - 1) tabindex='-1') Previous
            li.page-item.disabled
                a.page-link(href='#')
                    =currentPage
                    |  of 
                    =totalPages
            if currentPage == totalPages
                li.page-item.disabled
                    a.page-link(href= '/') Next
            else
                li.page-item
                    if suburb == null
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/'  + count) Next
                    else
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/' + suburb + '/' + count ) Next

(JAVASCRIPT)

const express = require('express');
const mysql = require('mysql');
const multer = require('multer');
const path = require('path');
const app = express();

const conn = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "",
    database: "realestate"
});

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/uploads");
    },
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: { filesize: 1000000 },
    fileFilter: function(req, file, cb) {
        checkFiletype(file, cb);
    }
}).single("myImage");

function checkFiletype(file, cb) {
    const filetypes = /jpeg|jpg|png|gif/;
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);
    if (mimetype && extname) {
        return cb(null, true);
    } else {
        cb('Error: Image Only!');
    }
}

app.use(express.static("public"));

app.set("view engine", "pug");
app.set("views", "./views");

app.get("/about", function(req, res){
    res.render('about', {
        title: 'About Us'
    })
});

app.get("/:suburb?/:page?", (req, res)=>{

    let suburb = req.params.suburb;
    let page = req.params.page || 1;
    let limit = 12;
    let offset;
    console.log(suburb);
    console.log(page);
    if (page == 1) {
        offset = 1;
    } else {
        offset = (page - 1) * limit + 1;
    }

    let sqlSuburbs = "SELECT DISTINCT suburb FROM properties ORDER BY suburb";
    let sqlProperties = "SELECT * FROM WHERE suburb = ?";
    let sqlCountPlaceholder = [suburb];
    let sqlCount = "SELECT COUNT(*) AS 'count' FROM properties WHERE suburb = ?";
    let placeholders = [suburb, limit, offset];

    if (suburb == parseInt(suburb)) {
        page = suburb;
        suburb = "";
        offset = (page - 1) * limit + 1;
        sqlProperties = "SELECT * FROM properties";
        placeholders = [limit, offset];
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        sqlCountPlaceholder = [suburb];
    }

    else if (suburb === undefined) {
        sqlProperties = "SELECT * FROM properties";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = ['suburb'];
        suburb = "";
    }
    else
    {
        sqlProperties = "SELECT * FROM properties where suburb = '" + suburb + "'";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties where suburb = '" + suburb + "' ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = [suburb];
    }
    console.log(placeholders);
    console.log(sqlProperties);
    // get the distinct suburbs
    conn.query(sqlSuburbs, (err, suburb_result) => {
        if (err) throw err
        // Get the properties
        conn.query(sqlProperties + " LIMIT ? OFFSET ?", placeholders, (err, properties_result)=>{
            if (err) throw err
            // Get the query record count
            conn.query(sqlCount, sqlCountPlaceholder, (err, record_count)=>{
                var totalPages = Math.ceil(record_count[0].count / limit);
                if (err) throw err

                if(suburb)
                {
                    suburb = '/' + suburb;
                }
                //Display the page and provide it with values
                res.render("index", {
                    title: 'Home Page',
                    suburbs: suburb_result,
                    properties: properties_result,
                    currentPage: page,
                    next: Number(page)+1 > totalPages?totalPages:Number(page)+1,
                    prev: Number(page)-1 >= 1?Number(page)-1:1,
                    totalPages: totalPages,
                    suburb: suburb
                });
            });
        });
    });
});


app.get("/admin/user/dashboard", (req, res)=>{
    res.render('admin/dashboard', {
        title: 'Dashboard'
    });
});

app.get("/admin/user/fileupload", (req, res)=>{
    res.render("admin/uploads", {
        title: 'File Upload Area'
    });
});



app.post("/admin/user/uploads", (req, res)=>{
    upload(req, res, (err)=> {
        if (err) {
            res.render("admin/uploads", {
                msg: err
            });
        } else {
            if (req.file == undefined) {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "Error: No File Selected!"
                })
            } else {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "File Uploaded!",
                    file: 'uploads/${req.file.filename}'
                });
            }
        }
    });
});

app.listen(3000, ()=>{

    console.log("Running on port 3000...")
});
...