Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unable to use pjax with express #246

Open
Godskull opened this issue Jul 24, 2022 · 0 comments
Open

unable to use pjax with express #246

Godskull opened this issue Jul 24, 2022 · 0 comments

Comments

@Godskull
Copy link

Godskull commented Jul 24, 2022

i m trying to run pjax with express my codes are as following

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var chalk = require('chalk');
var indexRouter = require('./routes/index');
var pjax = require('express-pjax');


var app = express();
//ddos prot
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ parameterLimit: 100000, limit: '50mb', extended: true }));
//config read
var config = require('config');
const port = config.get('server.port');

// view engine setup
app.use(pjax());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});
//run cmds
console.log(chalk.blue('Exec cmds being run'));
const { exec } = require("child_process");
exec("node bot.js", (error, data, getter) => {
    if (error) {
        console.log("error", error.message);
        return;
    }
    if (getter) {
        console.log("Bot:", data);
        return;
    }
    console.log("Bot started:", data);

});

console.log(chalk.blue.green.underline('panel started at:'), port);
module.exports = app;

www

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var database = require('../api/sqlConnection');
var debug = require('debug')('mywebsite:server');
var http = require('http');
var chalk = require('chalk');
/**
 * Get port from environment and store in Express.
 */
//config read
var config = require('config');
const port = config.get('server.port');

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);



// handle specific listen errors with friendly messages
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string' ?
        'Pipe ' + port :
        'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}


function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ?
        'pipe ' + addr :
        'port ' + addr.port;
    debug('Listening on ' + bind);
}

/views/index.ejs

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Hello</title>
    <script src="/pjax/pjax.js"></script>
    <script src="/public/javascripts/pjax.js"></script>
</head>

<body>
    <div class="body">
        <h1>Index</h1>
        Hello. Go to <a href="/views/page1.ejs" class="js-Pjax">Page 1</a>
    </div>
</body>

</html>

/public/javascripts/pjax.js

/* global Pjax */
var pjax;
var initButtons = function() {
    var buttons = document.querySelectorAll("button[data-manual-trigger]");

    if (!buttons) {
        return;
    }

    // jshint -W083
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", function(e) {
            var el = e.currentTarget;

            if (el.getAttribute("data-manual-trigger-override") === "true") {
                // Manually load URL with overridden Pjax instance options
                pjax.loadUrl("/views/page1.ejs", { cacheBust: false });
            } else {
                // Manually load URL with current Pjax instance options
                pjax.loadUrl("/views/page1.ejs");
            }
        });
    }
    // jshint +W083
};

console.log("Document initialized:", window.location.href);

document.addEventListener("pjax:send", function() {
    console.log("Event: pjax:send", arguments);
});

document.addEventListener("pjax:complete", function() {
    console.log("Event: pjax:complete", arguments);
});

document.addEventListener("pjax:error", function() {
    console.log("Event: pjax:error", arguments);
});

document.addEventListener("pjax:success", function() {
    console.log("Event: pjax:success", arguments);

    // Init page content
    initButtons();
});

document.addEventListener("DOMContentLoaded", function() {
    // Init Pjax instance
    pjax = new Pjax({
        elements: [".js-Pjax"],
        selectors: [".body", "title"],
        cacheBust: true
    });
    console.log("Pjax initialized.", pjax);

    // Init page content
    initButtons();
});

routes/index.js

var express = require('express');
var router = express.Router();
var pjax = require('express-pjax');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.renderPjax('index', { title: 'Welcome' });
});
router.get('/page1.ejs', function(req, res, next) {
    res.renderPjax('page1', { title: 'Welcome' });
});
module.exports = router;

when i run it no error comes but when i try to redirect it reloads the page instead of using pjax

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant