从app.js(节点)发送和检索数据到javascript(main.js)

时间:2017-06-28 17:20:35

标签: javascript html node.js

我想将数据(用户名)fom app.js发送到main.js,并从main.js检索数据(用户名)到app.js.我有app.js这是节点,调用index.html。 index.html实习生调用main.js函数点击。这是我的代码。

app.js

var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();

var username = 'username';

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

var request = require('request');
request('http://localhost:8000/test', function (error, response, body){
if (!error && response.statusCode == 200) {
console.log(body);
}
});

app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});

app.listen(3000,'127.0.0.1');
console.log('Listening on port 3000');

main.js

function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');

var checkuser = "test";
var checkpass = "123"

if (user.value == checkuser) {
    if (pass.value == checkpass) {
        window.location.href = "login.html";
    }
    else
    window.alert("Incorrect username or Password"); 
}
else
    window.alert("Incorrect username or Password");
}

请帮我解决这个问题。

的index.html

<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet"    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script  src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>

<center>
<h1>LOGIN</h1>
<form action="" method="get">
<div class="container-fluid">
<div class="well">
<input type="text" id="username" placeholder="UserName"></br>
<input type="password" id="password" placeholder="PassWord"></br>
<input type="button" value="Login" onclick="clicked()">
<!--<button type="submit" onclick="clicked()">Login</button>-->
<button type="submit" formaction="register.html">Register</button>
</div>
</div>
</form>
</center>

1 个答案:

答案 0 :(得分:2)

您应该使用EJS之类的模板引擎将数据传递到HTML页面。模板引擎通过组合HTML代码和包含逻辑和数据的脚本,生成最终的HTML响应,并将其发送到客户端。

我不知道您的用例,但将用户名和密码传递给客户端并验证客户端是一个坏主意。相反,您可以对服务器进行AJAX调用并在服务器端进行验证。希望它有所帮助。