[英]How to send a variable from nodejs file to ejs file
var express = require('express');
var app = express();
app.use("/", function(request, response){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Test");
dbo.collection("users").find({}, { "name":"John" }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
// res.sendFile(__dirname + "/views/index.ejs");
db.close();
});
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<h1 id="result"><%=result%></h1>
</body>
</html>
我有 2 個文件,我想在另一個文件中使用一個文件中的變量。 如何在<h1 id="result"><%=result%></h1>
中將我的 nodejs 文件中的變量result
發送到我的 ejs 文件?
為此,您必須根據文檔使用 express res.render()
res.render(view [, locals] [, callback]) 渲染視圖並將渲染后的 HTML 字符串發送到客戶端。 可選參數:locals,一個 object,其屬性定義視圖的局部變量。
你應該使用這樣的東西
res.render('index',{result});
那么現在您將能夠訪問您在 index.ejs 文件中發送的該值,但是我建議您在應用程序中明確聲明您正在使用 ejs ,這樣您就不必go 通過重新的斗爭在代碼的末尾聲明ejs,就像在這段代碼var app = express()
之后的頂部之前一樣,你可以說
app.set("view engine", "ejs");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.