Javascript 将变量从 node.js 传递到 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37991995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a variable from node.js to html
提问by vic-3
I am trying to pass a variable from node.js to my HTML file.
我正在尝试将 node.js 中的变量传递给我的 HTML 文件。
app.get('/main', function(req, res) {
var name = 'hello';
res.render(__dirname + "/views/layouts/main.html", {name:name});
});
回答by vic-3
I figured it out I was able to pass a variable like this
我发现我能够传递这样的变量
<script>var name = "<%= name %>";</script>
console.log(name);
回答by Vasil Dininski
What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:
您可以使用某种模板引擎,例如 pug(以前称为 jade)。要启用它,您应该执行以下操作:
npm install --save pug
- to add it to the project and package.json fileapp.set('view engine', 'pug');
- register it as a view engine in express- create a
./views
folder and add a simple.pug
file like so:
npm install --save pug
- 将其添加到项目和 package.json 文件中app.set('view engine', 'pug');
- 在 express 中将其注册为视图引擎- 创建一个
./views
文件夹并添加一个简单的.pug
文件,如下所示:
html
head
title= title
body
h1= message
note that the spacing is very important!
注意间距很重要!
- create a route that returns the processed html:
- 创建一个返回处理过的 html 的路由:
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html
这将呈现一个 index.html 页面,其中 node.js 中传递的变量更改为您提供的值。这直接取自 expressjs 模板引擎页面:http://expressjs.com/en/guide/using-template-engines.html
For more info on pug you can also check: https://github.com/pugjs/pug
有关 pug 的更多信息,您还可以查看:https: //github.com/pugjs/pug
回答by Pritam Jana
I found the possible way to write.
我找到了可能的写作方式。
Server Side -
服务器端 -
app.get('/main', function(req, res) {
var name = 'hello';
res.render(__dirname + "/views/layouts/main.html", {name:name});
});
Client side (main.html) -
客户端 (main.html) -
<h1><%= name %></h1>
回答by Tudor Leustean
With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>
, without any other stuff installed.
仅使用 Node 和 HTML,您将无法实现您想要的;这不像使用 PHP,您可以在其中执行类似的操作<title> <?php echo $custom_title; ?>
,而无需安装任何其他东西。
To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check thisout) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.
要使用 Node 做你想做的事,你可以使用一种叫做“模板”引擎的东西(比如 Jade,看看这个)或者在 Javascript 中使用一些 HTTP 请求从服务器获取你的数据并用它来替换部分HTML 与它。
Both require some extra work; it's not as plug'n'playas PHP when it comes to doing stuff like you want.
两者都需要一些额外的工作;在做您想做的事情时,它不像 PHP那样即插即用。
回答by Codemaker
To pass variables from node.js to html by using the res.render() method.
使用 res.render() 方法将变量从 node.js 传递到 html。
Example:
例子:
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render('index.html',{email:data.email,password:data.password});
});
回答by Bryam42
If using Express it's not necessary to use a View Engine at all, use something like this:
如果使用 Express,则根本不需要使用视图引擎,请使用以下内容:
<h1>{{ name }} </h1>
This works if you previously set your application to use HTML instead of any View Engine
如果您之前将应用程序设置为使用 HTML 而不是任何视图引擎,则此方法有效
回答by Patrick Knott
use res.json, ajax, and promises, with a nice twist of localStorage to use it anywhere, added with tokens for that rare arcade love. PS, you could use cookies, but cookies can bite on https.
使用 res.json、ajax 和 promises,加上 localStorage 的巧妙改造,可以在任何地方使用它,并为罕见的街机爱情添加了标记。PS,您可以使用 cookie,但 cookie 可以咬 https。
webpage.js
网页.js
function (idToken) {
$.ajax({
url: '/main',
headers: {
Authorization: 'Bearer ' + idToken
},
processData: false,
}).done(function (data) {
localStorage.setItem('name', data.name);
//or whatever you want done.
}).fail(function (jqXHR, textStatus) {
var msg = 'Unable to fetch protected resource';
msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
if (jqXHR.status === 401) {
msg += '<br>Your token may be expired'
}
displayError(msg);
});
server.js, using express()
server.js,使用 express()
app.get('/main',
passport.authenticate('oauth2-jwt-bearer', { session: false }),
function (req, res) {
getUserInfo(req) //get your information to use it.
.then(function (userinfo) { //return your promise
res.json({ "name": userinfo.Name});
//you can declare/return more vars in this res.json.
//res.cookie('name', name); //https trouble
})
.error(function (e) {console.log("Error handler " + e)})
.catch(function (e) {console.log("Catch handler " + e)});
});
回答by Sainudheen Sahib
I have achieved this by a http API node
request which returns required object from node object for HTML
page at client ,
我通过一个http API node
请求实现了这一点,该请求从节点对象返回HTML
客户端页面所需的对象,
for eg: API: localhost:3000/username
例如: API: localhost:3000/username
returns logged in user from cache by node App object .
通过节点 App 对象从缓存中返回登录用户。
node route file,
节点路由文件,
app.get('/username', function(req, res) {
res.json({ udata: req.session.user });
});
回答by zaffar
Other than those on the top, you can use JavaScript to fetch the details from the server. html file
除了顶部的那些,您可以使用 JavaScript 从服务器获取详细信息。html文件
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="test">
</div>
<script type="text/javascript">
let url="http://localhost:8001/test";
fetch(url).then(response => response.json())
.then( (result) => {
console.log('success:', result)
let div=document.getElementById('test');
div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
})
.catch(error => console.log('error:', error));
</script>
</body>
</html>
server.js
服务器.js
app.get('/test',(req,res)=>{
//res.sendFile(__dirname +"/views/test.html",);
res.json({title:"api",message:"root"});
})
app.get('/render',(req,res)=>{
res.sendFile(__dirname +"/views/test.html");
})
The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer
我在上述主题的堆栈溢出中找到的最佳答案,这不是我的答案。在某处找到了几乎相同的问题...... 答案的来源