如何在实时浏览器中运行 Node JS 文件

问题描述 投票:0回答:1

我正在尝试创建一个包含输入字段和按钮的 html 页面。一旦用户单击按钮,我希望页面运行 Node JS 文件。

目前,html 脚本仅显示输入,但我会将输入链接到 Node JS 文件中的函数中,并显示/存储输出。

据我了解,这只能在实时浏览器中实现。我尝试使用 npm live-server 以及 VScode live-server 扩展。

但是,每当我启动服务器时,我都会在控制台中收到此错误。

GET http://127.0.0.1:8080/RecipeScrapper/index.js net::ERR_ABORTED 404 (Not Found)
In the** Network tab** the summary says:
Request URL: http://127.0.0.1:8080/RecipeScrapper/index.js
Request Method: GET
Status Code: 404 Not Found
Referrer Policy: strict-origin-when-cross-origin

这是我的文件结构

Desktop
| -- node_modules(folder)
| -- index.html
| -- index.js
| -- package.json
| -- package-lock

html文件的相关部分:

<head>
    <Title>Recipe</Title>
    <script type="module" src="/RecipeScrapper/index.js"></script>
</head>
<body>
    ... 
    <button onclick= "Display(document.getElementById('a').value)"> Display Link </button>
 </body>

index.js相关部分

import * as cheerio from 'cheerio';
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
async function getItems(a) { 
    try {
      const response = await fetch (a); 
      const body = await response.text();
      const $ = cheerio.load(body);
      const $wrapper4 = $('[data-test-id= "ingredients-list"] [data-test-id="ingredient-item-shipped"]');
      let uitems = [];

      $wrapper4.each((i, div) => {
        uitems.push($(div).text());
    });
    for(let i=0; i<uitems.length; i++)
    {
     ...
    }
    //print
    console.log(uitems)
    } catch (error) {
      console.log(error);
    }
  }
getItems('https://www.hellofresh.com/recipes/peppercorn-steak-w06-5857fcd16121bb11c124f383');

文件存储库:https://github.com/Anthony-S4/RecipeScrapper

我对 Web 开发非常陌生,我可能误解了 NodeJs 和 JS 文件之间的区别。 据我所知,使用实时浏览器应该可以完成此任务。如果我被误解了,请解释一下浏览器中使用的 NodeJS 和 JS 文件之间的区别,我们将不胜感激。

javascript html node.js server node-modules
1个回答
1
投票

据我所知,使用实时浏览器应该可以完成此任务。

事实并非如此。在网络浏览器中运行的 JavaScript 无权访问其他网站上的数据,除非该网站给出明确许可

如果我被误解了,请解释一下浏览器中使用的 NodeJS 和 JS 文件之间的区别,我们将不胜感激。

此处相关的主要区别是:

  • Node.js 可以通过搜索文件系统来解析模块名称,而浏览器则处理 URL
  • Node.js 和浏览器有不同的可用 API(例如 Node.js 可以向任何 URL 发出任何 HTTP 请求并读取响应)。

有关如何创建程序/网站来完成此任务的任何指示也将不胜感激

使用 Node.js 编写 Web 服务器。 Express 是一个流行的库来做到这一点。从 Express.js 端点调用依赖于 Node.js 的代码。让浏览器向该端点发出 HTTP 请求(例如,通过提交 form 或使用 Ajax)。

© www.soinside.com 2019 - 2024. All rights reserved.