我遇到EJS文件未按预期呈现的问题。我正在使用ExpressJS和MongoDB。当我从数据库中获取数据时,它会呈现到页面上,但是EJS模板中的HTML都不会被呈现。我怀疑问题出在我的router.get()调用上,但是到目前为止我一直无法解决问题。
我当前的代码如下:
Index.js
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import "./App.css";
import Navigation from "./components/Navigation";
import Sidebar from "./components/Sidebar";
import Game from "./components/games";
import Profile from "./components/Profile";
import NotFound from "./components/Notfound";
class App extends Component {
constructor(props) {
super(props);
this.state = {
gameFetched: "false",
searchTerm: ""
};
}
getSearch = e => {
if (e.key === "Enter") {
this.setState({
searchTerm: e.target.value
});
this.fetchIGBD()
}
};
componentDidMount() {
this.fetchIGBD();
}
render() {
return (
<div className="App">
<BrowserRouter>
<div>
<Navigation getSearch={this.getSearch} />
<div id="main-wrapper" className="d-flex">
<Sidebar />
<div id="content">
<Switch>
<Route path="/" component={Game} exact />
<Route path="/profile" component={Profile} />
<Route component={NotFound} />
</Switch>
</div>
</div>
</div>
</BrowserRouter>
</div>
);
}
fetchIGBD = () => {
let url = "http://localhost:8080/api-v3.igdb.com/games";
let data ="fields name,cover,first_release_date,genres.name,platforms.name,total_rating;limit 10;sort popularity;where total_rating > 80;where release_dates.platform = 6;";
let search = "search '"+this.state.searchTerm+"';";
if (search !== "") {
data = data + search
console.log(data)
}
fetch(url, {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
"user-key": "myid"
}
})
.then(res => res.json())
.then(json => console.log(json))
.catch(error => console.log(error));
this.setState({
gameFetched: "true"
});
};
}
export default App;
userlist.ejs
var express = require("express");
var router = express.Router();
/* GET Userlist page */
router.get("/userlist", function (req, res) {
var db = req.db;
var collection = db.get("usercollection");
collection.find({}, {}, function (e, docs) {
res.render("userlist", {
"userlist": docs
});
});
});
module.exports = router;
如果任何人都可以识别语法错误并提出更正建议,将不胜感激。
答案 0 :(得分:1)
我认为问题出在您的ejs文件中。尝试以下循环:
<ul>
<% for (var item of userlist) { %>
<li><a href="mailto:<%= item.email %>"><%= item.username %></a></li>
<% } %>
</ul>