位于应用程序中的服务器端对象.js在我的 index.ejs 文件中标记为未导出



我在引用位于我的应用程序.js文件中的对象时遇到问题。我正在使用 express 运行我的服务器,对于视图引擎,我使用的是 EJS。
该对象在 app.js 文件中创建,然后在我的 PowerList.ejs 文件(索引文件)中使用。但是当尝试使用它时,它被标记为未导出。

应用程序中的对象和功能.js:

var number = {count: 0};
var profile = {name: 'My name', age: 21, job: 'My profession', hobbies: ['hiking', 'running', 'coding']};
app.get('/', function (req, res) {
res.render('PowerList.ejs',{data: profile, number: number}); 
});

PowerList.ejs 中使用的对象:

<section id="history" style="background-color: red; margin: auto; height: 400px; width: 650px; text-align: center; display: none">
<button id="button">click me</button>
<p>You have clicked me <%= number.count%> times</p>
</section>

让我感到困惑的是,正如您在代码片段中看到的那样,还有另一个称为配置文件的对象,它在我的 PowerList.ejs 文件中以相同的方式使用,并且没有引起任何问题。

配置文件对象用法:

<section id="productivity" style="background-color: bisque; margin: auto; height: 400px; width: 650px; text-align: center; display: none">
<p><strong>Profile name: </strong> <%= profile.name%></p>
<p><strong>Age: </strong><%= profile.age%></p>
<p><strong>Job: </strong><%= profile.job%></p>
<ul><strong>hobbies:</strong>
<% profile.hobbies.forEach(function (value) {  %>
<li><%= value %></li>
<%});%>
</ul>
</section>

我还在 javascript 文件中使用 number 对象,单击按钮后它会递增。在这里它也被标记为未导出,而且我在尝试通过单击按钮递增它时出现错误。

JavaScript 文件:

document.getElementById('button').addEventListener('click', loadNumber);
function loadNumber() {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', '/', true);
xhttp.onload = function () {
if(this.status === 200){
number.count++;
}
};
xhttp.send();
}

错误日志:

Uncaught ReferenceError: number is not defined
at XMLHttpRequest.xhttp.onload (addDelete.js:67)

你的错误:

var number = {count: 0};
var profile = {name: 'My name', age: 21, job: 'My profession', hobbies: ['hiking', 'running', 'coding']};
app.get('/', function (req, res) {
res.render('PowerList.ejs',{data: profile, number: 
^^^^^^^^
});

您有两种方法可以解决此问题,或者正常方法:

number: number

或者你只是删除":",它应该是好的:)

最新更新