NodeJS API结果未显示在index.ejs中,但控制台日志在index.js中工作

jq6vz3qz  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(109)

我试图添加一个API到一个项目,我得到了index.js来控制台记录结果,它工作得很好,但是,我似乎不明白如何在我的index.ejs上显示

import express from "express";
import axios from "axios";

const app = express();
const port = 3000;
const urlAndKey = "https://newsapi.org/v2/everything?q=bitcoin&apiKey=7160918468a64df9a7bf26e5915c1f50";

app.get("/", (req, res) => {
  res.render("index.ejs", { content: "Your news will display here." });
});


  app.get("/apiKey", async (req, res) => {
    try {
      const result = await axios.get(urlAndKey);
      console.log(result.data);
      res.render("index.ejs", { content: result.data });
    } catch (error) {
      res.status(404).send(error.message);
    }
  });

app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
  });

个字符
我试图显示新闻文章的文本区域的ejs文件我已经尝试了内容。文章。标题,<%=内容%>和一些更多,我不能弄清楚我错过了什么

ffvjumwh

ffvjumwh1#

以下是如何修改代码:
创建一个名为“news.ejs”的新EJS模板:

<!-- news.ejs -->
<div class="container col-7">
    <div class="row">
        <% for (const article of content.articles) { %>
            <div class="col-12 mt-3">
                <h2><%= article.title %></h2>
                <p><%= article.description %></p>
                <a href="<%= article.url %>" target="_blank">Read More</a>
            </div>
        <% } %>
    </div>
</div>

字符串
修改服务器代码,以便在获取新闻数据时呈现“news.ejs”模板:

// Server code
import express from "express";
import axios from "axios";

const app = express();
const port = 3000;
const apiKey = "YOUR_NEWS_API_KEY"; // Replace with your actual API key

app.set("view engine", "ejs"); // Set EJS as the view engine
app.use(express.static("public")); // Serve static assets from the "public" folder

app.get("/", (req, res) => {
res.render("index.ejs");
});

app.get("/news", async (req, res) => {
try {
    const url = `https://newsapi.org/v2/everything?q=bitcoin&apiKey=${apiKey}`;
    const response = await axios.get(url);
    const newsData = response.data;
    res.render("news.ejs", { content: newsData });
} catch (error) {
    res.status(500).send(error.message);
}
});

app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});


修改您的index.ejs以包含指向“/news”路由的链接:

<!-- index.ejs -->
<div class="container col-7">
    <div class="row">
        <div class="col-4">
            <a href="/news" class="btn btn-primary pill-rounded">Get All The News</a>
        </div>
    </div>
</div>

相关问题