gpt4 book ai didi

Javascript 代码未在 PUG/Jade 文件上运行

转载 作者:行者123 更新时间:2023-12-03 02:06:55 25 4
gpt4 key购买 nike

我正在按照本教程使用 socket.io 实现井字棋游戏: https://ayushgp.github.io/Tic-Tac-Toe-Socket-IO/ .

但我也想使用登录系统。

当用户登录时,它成功进入此页面(我将html转换为pug),位于/views/game.pug

doctype html
html
head
title Tic Tac Toe
link(rel='stylesheet', href='/css/main.css')
link(rel='stylesheet', href='/node_modules/skeleton-css/css/skeleton.css')
body
.container
.menu
h1 Tic - Tac - Toe
h3 How To Play
ol
li Player 1 Create a new game by entering the username
li
| Player 2 Enter another username and the room id that is displayed on first window.
li Click on join game.
h4 Create a new Game
input#nameNew(type='text', name='name', placeholder='Enter your name', required='')
button#new New Game
br
br
h4 Join an existing game
input#nameJoin(type='text', name='name', placeholder='Enter your name', required='')
input#room(type='text', name='room', placeholder='Enter Game ID', required='')
button#join Join Game
.gameBoard
h2#userHello
h3#turn
table.center
tr
td
button#button_00.tile
td
button#button_01.tile
td
button#button_02.tile
tr
td
button#button_10.tile
td
button#button_11.tile
td
button#button_12.tile
tr
td
button#button_20.tile
td
button#button_21.tile
td
button#button_22.tile
.container
script(src='/node_modules/jquery/dist/jquery.min.js')
script(src='/socket.io/socket.io.js')
script(src='/js/main2.js')

效果很好。但是当我单击 id #new 的按钮时,什么也没有发生。这是我收到的错误:/image/NwrVc.png .

这是main2.js的相关部分,位于/public/js/main2.js:

  $('#new').on('click', () => {
const name = $('#nameNew').val();
if (!name) {
alert('Please enter your name.');
return;
}
socket.emit('createGame', { name });
player = new Player(name, P1);
});

编辑:

文件位置:

ma​​in.css 位于/public/css/main.css

骨骼.css 位于/node_modules/骨骼-css/css/骨骼.css

jquery.min.js 位于/node_modules/jquery/dist/jquery.min.js

socket.io.js 位于/node_modules/socket.io-client/dist/socket.io.js

/public/js/main2.js 上的

ma​​in2.js

app.js(仅显示相关部分):

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
app.use(express.static('.'));
//Load View engine
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

//Set public folder
app.use(express.static(path.join(__dirname, 'public')));

//This get request is sent after the user logs in. It works fine
app.get('/users/game', function(req, res) {
res.render('game', {
title:'Game'
});
});

io.on('connection', (socket) => {
//See full code here:https://github.com/ayushgp/tic-tac-toe-socket-io/blob/master/index.js
}

let articles = require('./routes/articles');
let users = require('./routes/users');
app.use('/articles', articles);
app.use('/users', users);

此外,我的 main2.js 文件与此文件相同:https://github.com/ayushgp/tic-tac-toe-socket-io/blob/master/main.js

编辑2:完整的 app.js 代码(相关部分是对用户/游戏的 get 请求:

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const config = require('./config/database');
const passport = require('passport');

let rooms = 0;

app.use(express.static('.'));

mongoose.connect(config.database, {
useMongoClient: true
});
let db = mongoose.connection;

//Check connection
db.once('open', function(){
console.log('Connected to MONGOdb')
});

//Check for DB errors
db.on('error', function(err){
console.log(err);
});

//Bring in models
let Article = require('./models/article');

//Load View Engine
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Boddy parser middlware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//Set public folder
app.use(express.static(path.join(__dirname, 'public')));

//Express Session Middleware
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));

//Express Messages Middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});

//Express Messages Middleware
app.use(expressValidator());

//Passport Config
require('./config/passport')(passport);
//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

app.get('*', function(req, res, next){
res.locals.user = req.user || null;
next();
});


//Home ROute
app.get('/', function(req, res) {
Article.find({}, function(err, articles){
if(err){
console.log(err);
} else {
res.render('index', {
title:'Articles',
articles: articles
});
}
});
});

app.get('/users/game', function(req, res) {
res.render('game', {
title:'Game'
});
});

io.on('connection', (socket) => {

// Create a new game room and notify the creator of game.
socket.on('createGame', (data) => {
socket.join(`room-${++rooms}`);
socket.emit('newGame', { name: data.name, room: `room-${rooms}` });
});

// Connect the Player 2 to the room he requested. Show error if room full.
socket.on('joinGame', function (data) {
var room = io.nsps['/'].adapter.rooms[data.room];
if (room && room.length === 1) {
socket.join(data.room);
socket.broadcast.to(data.room).emit('player1', {});
socket.emit('player2', { name: data.name, room: data.room })
} else {
socket.emit('err', { message: 'Sorry, The room is full!' });
}
});

/**
* Handle the turn played by either player and notify the other.
*/
socket.on('playTurn', (data) => {
socket.broadcast.to(data.room).emit('turnPlayed', {
tile: data.tile,
room: data.room
});
});

/**
* Notify the players about the victor.
*/
socket.on('gameEnded', (data) => {
socket.broadcast.to(data.room).emit('gameEnd', data);
});
});

//Route files
let articles = require('./routes/articles');
let users = require('./routes/users');
app.use('/articles', articles);
app.use('/users', users);


//Start Sever
app.listen(3000, function() {
console.log('Server running');
});

最佳答案

代码块将不起作用:

script(src='node_modules/jquery/dist/jquery.min.js')

请尝试这样:

app.use('/scripts', 
express.static(path.join(__dirname, 'node_modules/jquery/dist')),
// add some others
);

app.use('/styles',
express.static(path.join(__dirname, '/node_modules/skeleton-css/css')),
// add some others
);

查看中:

script(src='/scripts/jquery.min.js')
link(type='text/stylesheet' href='/styles/skeleton.css')

并且您不需要套接字客户端的 socket-io-client 模块。

在你的代码块上,如果你想要同一原始主机的套接字连接,则不需要socket-io-client模块。

如果您使用socket.io创建了套接字服务器,则可以在使用 View 模板时包含这样的socket.io脚本。

script(type='text/javascript', src='/socket.io/socket.io.js')

关于Javascript 代码未在 PUG/Jade 文件上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49762545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com