gpt4 book ai didi

javascript - 在 <script> node.js 中需要函数

转载 作者:行者123 更新时间:2023-11-30 15:14:57 26 4
gpt4 key购买 nike

我可以在脚本标签中放置一个 require 函数吗?例如:

<script>
var User = require('../models/user');
alert('It is working');
</script>

上面的代码是我的layout.handlebar代码。但它似乎不起作用。因为我需要获取此脚本,以便我可以在我的 handlebar 模板引擎上访问 user.js 脚本。

user.js

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

//User Schema
var UserSchema = mongoose.Schema({
username:{
type: String,
index:true
},
password:{
type:String
},
email:{
type:String
},
name:{
type:String
},
field:{
type:String
},
e_money:{
type:Number //this is the integer form in mongoose
}
});

//accesible variable from the outside
var User = module.exports = mongoose.model('User', UserSchema);

//create the user
module.exports.createUser= function(newUser, callback){
bcrypt.genSalt(10, function(err,salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
//store hash in your password DB
newUser.password = hash;
newUser.save(callback);
});
});
}



module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
}

已编辑:我编辑了我的问题,因为我真正想要的是当我单击按钮时它会在我的数据库中更新。这是我的全部代码

在我的路线上->users.js

//To run the application
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

//Register
router.get('/register', function(req,res){
res.render('register');
});

//Login
router.get('/login',function(req,res){
res.render('login');
});

//Register User
router.post('/register', function(req,res){
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
var field = req.body.field;

//temporary for emoney
var e_money = req.body.e_money;

//show what's been written in web to console(name)
//console.log(name);

//validation - Check to see if the field is empty
req.checkBody('name', 'Name is required!').notEmpty();
req.checkBody('email', 'Email is required!').notEmpty();
req.checkBody('email', 'Email is not valid!').isEmail();
req.checkBody('username', 'Username is required!').notEmpty();
req.checkBody('password', 'Password is required!').notEmpty();
req.checkBody('password2', 'Password does not match').equals(req.body.password);
req.checkBody('field', 'Please specify if you are a Teacher or a Student!').notEmpty();

//temporary for emoney
req.checkBody('e_money','Please add some value in this field').notEmpty();

var errors = req.validationErrors();

if(errors){
res.render('register',{
errors:errors
});
}else{
//new user in the model(user.js)
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney
});

User.createUser(newUser,function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'You are registed and can now login');

res.redirect('/users/login');
}
});




passport.use(new LocalStrategy(
function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}

User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
}
else{
return done(null, false, {message: "Invalid password"});
}
});
});
}));

passport.serializeUser(function(user, done){
done(null, user.id);
});

passport.deserializeUser(function(id, done){
User.getUserById(id, function(err, user){
done(err,user);
});
});

router.post('/login',
passport.authenticate('local',{sucessRedirect:'/',failureRedirect:'/users/login',failureFlash: true}),
function(req,res){
//dashboard
if (req.user.field == "student") {
req.flash('stud_val', 'student');
}else if(req.user.field == "teacher"){
req.flash('teach_val', 'teacher');
}else if (req.user.field == "admin") {
req.flash('admin_val', 'teacher');
}
res.redirect('/');
});

router.get('/logout',function(req, res){
req.logout();
req.flash('success_msg', 'You are logged out');

res.redirect('/users/login');
})


module.exports = router;

在我的views->layout->layout.handlebars

<!DOCTYPE html>
<html>
<head>
{{#if user}}
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<title>PEKTOS | Live Stream</title>
<!-- Favicon-->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">
<!-- Bootstrap Core Css -->
<link href="plugins/bootstrap/css/bootstrap.css" rel="stylesheet">
<!-- Waves Effect Css -->
<link href="plugins/node-waves/waves.css" rel="stylesheet" />
<!-- Animation Css -->
<link href="plugins/animate-css/animate.css" rel="stylesheet" />
<!-- Morris Chart Css-->
<link href="plugins/morrisjs/morris.css" rel="stylesheet" />
<!-- Custom Css -->
<link href="css/style.css" rel="stylesheet">
<!-- AdminBSB Themes. You can choose a theme from css/themes instead of get all themes -->
<link href="css/themes/all-themes.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/easyrtc/easyrtc.js"></script>
<script type="text/javascript" src="/easyrtc/labs/easyrtc_recorder.js"> </script>
{{#if stud_val}}
<script type="text/javascript" src="js/demo_multistream_stud.js"></script>
{{/if}}
{{#if teach_val}}
<script type="text/javascript" src="/easyrtc/labs/desktop_capture_iframe_version.js"></script>
<script type="text/javascript" src="js/demo_multistream.js"></script>
{{/if}}
<!-- <script type="text/javascript" src="js/demo_instant_messaging_rooms.js"></script> -->

<!-- for button -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script type="text/javascript" src="prettify/prettify.js"></script>
<script type="text/javascript" src="js/jquery.slimscroll.js"></script>



{{else}}
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<title>Pektos | Log in</title>
<!-- Favicon-->
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">

<!-- Bootstrap Select Css -->
<link href="plugins/bootstrap-select/css/bootstrap-select.css" rel="stylesheet" />

<!-- Bootstrap Core Css -->
<link href="/plugins/bootstrap/css/bootstrap.css" rel="stylesheet">

<!-- Waves Effect Css -->
<link href="/plugins/node-waves/waves.css" rel="stylesheet" />

<!-- Animation Css -->
<link href="/plugins/animate-css/animate.css" rel="stylesheet" />

<!-- Custom Css -->
<link href="/css/style.css" rel="stylesheet">



{{/if}}
</head>
<!--Load view-->
{{#if user}}
<body class="theme-red" style="overflow: hidden;">
{{{body}}}
{{else}}
<body class="login-page">
<div class="login-box">
<div class="logo">
<a href="javascript:void(0);">Pek<b>Tos</b></a>
<small>Right On Target</small>
</div>
<div class="card">
<div class="body">
<form id="sign_in" method="POST">
<div class="msg">
{{#if success_msg}} <!--Global variable that has been set in app.js-->
<div class="alert alert-success">{{success_msg}}
</div>
{{/if}}
{{#if error_msg}}
<div class="alert alert-danger">{{error_msg}}
</div>
{{/if}}
{{#if error}}
<div class="alert alert-danger">{{error}}
</div>
{{/if}}
{{{body}}}
</div>
</form>
</div>
</div>
</div>
{{/if}}
{{#if user}}

<script>

$('#localVideos').click(function(){
$('nav').toggle('drop',{direction: 'up'}, 500);
$('.btnMenuFloat').toggle('drop',{direction: 'left'}, 500);
$('.actionBtnFloat').toggle('drop',{direction: 'down'}, 500);
$('.btnfloat').toggle('drop',{direction: 'down'}, 500);
$('.actionPanel2').hide();
});

function muteMe(id) {
if($('.cv'+id).prop('muted')){
$('.cv'+id).prop('muted', false);
var child = document.getElementById("micid"+id);
child.innerHTML = "mic";
$('.micbut'+id).css("color", "green");
}
else{
$('.cv'+id).prop('muted', true);
var child = document.getElementById("micid"+id);
child.innerHTML = "mic_off";
$('.micbut'+id).css("color", "red");
}
}

function showMe(id) {
$('#span'+id).toggle("drop",{direction: 'right'},500);
}

$(document).ready(function(){
var socket = io();

//understand button
$(".understandbtn").click(function(){
//reset the timer every 3 second of interval
$('.actionBtnFloat').css('z-index','0');

//电子货币

           var deduct = 100;
var newMoney = {{user.e_money}} - deduct;

alert("Your money is: "+ newMoney);
//i want to update here my e-money to the database with the value of the newMoney

//结束

            clearTimeout(interval);
//send the data to the server
socket.emit('chat message', getUser());
var interval = setTimeout(function(){
$('.'+getUser()).fadeIn();
},5000);
});

socket.on('chat message', function(msg){
$('.cv'+msg).fadeOut();
$('.'+msg).append('<img id="bulb" class="actImage" src="images/understand button.png" width="50" height="50">');
$('#say'+msg).html('I understand');
var intervals = setTimeout(function(){
$('#say'+msg).html('');
$('#bulb').remove();
$('.cv'+msg).fadeIn();
},5000);
});

//understand button end

最佳答案

不,您不能在浏览器中要求

服务器端 JavaScript (NodeJS) 和客户端 JavaScript 之间存在很大差异。客户端 JavaScript 还没有模块系统,您不能在 JavaScript 文件中导入/导出内容。

这对 JavaScript 来说是一个巨大的劣势,会产生很多问题。例如,多个 JS 文件如果要相互通信,则依赖于全局命名空间。

当 NodeJS 被引入时,它的创建者意识到了这个问题并创建了 require/module.exports 模式。如果您希望客户端 JavaScript 具有相同的行为,则必须使用模块 bundler ,例如 Rollup , Webpack , browserify

客户端 JavaScript 用于用户交互,而 NodeJS 几乎可以做任何你想做的事情(在服务器硬盘驱动器上读取/写入文件,访问数据库,...);但它只能在服务器上运行。

在客户端 JavaScript 中,您不能需要 mongoose 模块,因此,您不能访问服务器上的数据库。

此外,客户端 JavaScript 甚至不需要访问服务器的数据库。如果可以的话,那将是一种安全隐患。

如果你真的需要从数据库传输数据到浏览器,使用AJAX .

当然,WebSockets 是另一种在客户端和服务器之间传输数据的可能性。因为您已经在使用它们(我怀疑是 socket.io),所以这里有一个如何执行此操作的示例(我想这是您想要在客户端代码中触发数据库更新的地方):

$(".understandbtn").click(function () {
//reset the timer every 3 second of interval
$('.actionBtnFloat').css('z-index','0');
var deduct = 100;
var newMoney = {{user.e_money}} - deduct;

// send a message to the server that the e-money value has changed
socket.emit('update e-money', {
userName: {{user.name}}
newMoney: newMoney
});

clearTimeout(interval);
// send the data to the server
socket.emit('chat message', getUser());
var interval = setTimeout(function () {
$('.'+getUser()).fadeIn();
}, 5000);
});

socket.on('update e-money response', function (data) {
alert("Your money is: "+ data.newMoney);
});

socket.on('update e-money error', function (data) {
alert("Could not update your money: "+ data.error);
});

在服务器上,你会这样做:

// perhaps you gave the socket server variable a different name than "socket" 
socket.on('update e-money', function (data) {
var userName = data.userName;
var newMoney = data.newMoney;
var query = { username: userName };

// is this the way you update entries in the database?
User.findOneAndUpdate(query, { e_money: newMoney }, { upsert: true }, function (err, doc) {
if (err) {
socket.emit('update e-money error', { error: err });
}
socket.emit('update e-money response', { newMoney: newMoney });
});
});

关于javascript - 在 &lt;script&gt; node.js 中需要函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44612571/

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