【问题标题】:Responding an Array to another js file how?如何响应一个数组到另一个 js 文件?
【发布时间】:2020-04-16 18:45:27
【问题描述】:

我正在尝试将一个数组响应另一个 js 文件并从那里访问它。

我尝试res.render(),但它给我一个错误,我没有模块,我不想安装任何模块。

我也尝试了res.json(),但这只是在浏览器上显示了数组,我对此无能为力。

导入和导出不起作用。

获取此数组的特定 url fetch(/anime) 也不起作用,因为当我尝试启动我的服务器时,url("/") 它试图获取我尚未发送的数组。这是因为我发送的是html文件,它链接到另一个js文件。

希望我说清楚。

服务器.js

app.get("/", (req, res) => {
    app.use(express.static("./animeCatcher"));
    res.sendFile("index.html");
})

app.get("/anime", (req, res) => {
   let animeNames = ["One Piece", "Fairy Tail", "Attack on Titan"];
   res.json(animeNames);
        });

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src= "animeScrape.js"></script>
</head>
<body>

</body>
</html>

animeScraper.js

fetch('/anime')
   .then(res => res.json())
   .then(animeNames => console.log(animeNames));

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript html arrays node.js express


    【解决方案1】:

    请使用res.send(animeNames)res.status(200).send(animeNames)

    另外,请从路由中删除 express.static 并使其成为全局中间件:

    
    app.use(express.static("./animeCatcher"));
    
    app.get('/', (req, res) => {
        res.sendFile(`${__dirname}/index.html`);
    });
    
    app.get('/anime', (req, res) => {
        let animeNames = ["One Piece", "Fairy Tail", "Attack on Titan"];
        res.json(animeNames);
    });
    

    您的前端脚本是正确的,但是如果您的 API 调用显示为 fetch 类型,您能否在网络选项卡中签入:

    【讨论】:

    • 嘿 Mihir 感谢您抽出宝贵的时间,但如果我 res.send(animeNames) 则它只是显示在浏览器上。你知道我如何在我的其他 js 文件中使用这个变量吗??
    • 嗨@GeorgeHem 请检查我最近的编辑以回答
    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2020-05-09
    • 2021-09-14
    • 2015-09-07
    • 1970-01-01
    • 2022-01-22
    • 2018-07-23
    • 2018-02-19
    相关资源
    最近更新 更多