【问题标题】:How to direct node.js script output to text area in html page?如何将 node.js 脚本输出定向到 html 页面中的文本区域?
【发布时间】:2020-07-08 09:37:09
【问题描述】:

我有一个 node.js 脚本,我在其中发出了一个休息请求(在这种情况下是一个 GET 请求)。 当我从命令行运行脚本时,输出会很好地显示在控制台中。 我想将输出显示到一个 html 页面(换句话说 - 我想最终从网页运行这个脚本)。

我创建了两个 node.js 脚本 - 一个用于其余请求,一个用于将输出定向到 html 页面。

休息请求脚本:

const request = require('request-promise')
const readline = require('readline')

const options = {
    method: 'GET',
    uri: 'http://dummy.restapiexample.com/api/v1/employees'
}
request(options)
    .then(function (response) {
        // Request was successful, use the response object at will
        json: true
        //console.dir(response)
        JSON.parse(response)
        console.dir((JSON.parse(response)), {depth: null, colors: true})

    })
    .catch(function (err) {
        // Something bad happened, handle the error
    })

let currentResult = request

outputResult(currentResult);
function outputResult(result) {
    currentResult = (request);
}

输出导向器到 html 页面:

const restProto = document.getElementById('protocol');
const apiToTest = document.getElementById('uri');
const testApiResult = document.getElementById('output');

const currentResultOutput = document.getElementById('output');

function outputResult(result) {
    currentResultOutput.textContent = result;
}

这是我试图指向的 html 页面:

<!DOCTYPE html>
<html>
<body>
<head>
<meta name="viewport" content="width=device-width" initial-scale=1" charset="UTF-8">
<style>
    .collapsible {
        background-color: white;
        color: black;
        cursor: pointer;
        padding: 1px;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
    }

    .active, .collapsible:hover {
        background-color: #f1f1f1;
    }

    .content {
        padding: 0 18px;
        display: none;
        overflow: hidden;
        background-color: #f1f1f1;
    }
</style>
</head>

<h2>API Test (v 0.1 alpha)</h2>

<form>
    <label for="protocol">protocol</label>
    <select name="restcall" id="protocol">
        <option value="get">GET</option>
        <option value="put">PUT</option>
        <option value="post">POST</option>
        <option value="delete">DELETE</option>
    </select> &nbsp;&nbsp;

    <label for="uri">  url: </label>
    <input type="text" id="uri" name="uri">
    <br><br>

    <button class="collapsible">Advanced</button>
    <div class="content">
        <br>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
            commodo consequat.</p><br>
    </div>

    <br><br>
    <input type="submit" value="Send">
    <br><br>

</form>

<textarea id="output" name="output" rows="20" cols="50">
    Response displays here ...
</textarea>

<script>
    var coll = document.getElementsByClassName("collapsible");
    var i;

    for (i = 0; i < coll.length; i++) {
        coll[i].addEventListener("click", function() {
            //this.classList.toggle("active");
            var content = this.nextElementSibling;
            if (content.style.display === "block") {
                content.style.display = "none";
            } else {
                content.style.display = "block";
            }
        });
    }

</script>

<script src="./apitest2.js"></script>
<script src="./apitest3.js"></script>
<script src="./responseDirector.js"></script>

</body>
</html>

为了使这段代码正常工作,我缺少什么?

【问题讨论】:

  • 几件事。 1. 我对这段代码的执行感到惊讶,因为回调函数中间的json: true 是无效的语法。您应该在运行时崩溃。 2. let currentResult = request 只是将request 模块复制到一个新变量中。 3. currentResult = (request) 只是将request 模块复制到一个新变量中......带括号:) 4. 你的获取函数是异步的,你在.then 中得到它的结果,但是你什么都不做。你只有console.dir它,然后死路一条。
  • 我也不懂I want to direct the output to an html page.direct是什么意思? “指导页面”是什么意思?
  • @JeremyThille 感谢您的回复。你能告诉我如何修复我的代码吗?我是 nodeJS 的新手。我参加了一些在线课程,但经验是最好的老师。非常感谢您给我的任何指示。
  • @JeremyThille :我想将输出显示到 html 页面。换句话说,目的是通过一个 html 页面运行这个脚本。
  • 是的,现在写一个分析器。给我一分钟

标签: javascript node.js output


【解决方案1】:

我相信您正在尝试从 Node 加载 HTML 页面,然后像在浏览器中加载接收到的 HTML 以访问其 DOM 元素?这是典型的网络抓取场景。

无意冒犯,但是您的代码在全球范围内都是错误的(这在您学习时很正常),以至于我无法纠正所有错误,我认为将其全部重写会更快:)

import * as cheerio from 'cheerio';
const axios = require('axios').default; // "request" is a deprecated package. Use Axios instead.

const fetchHTML = async(url) => {

    const options = {
        url,
        timeout: 10000,
        responseType: 'text',
    };

    let response;

    try {
        response = await axios(options);
    } catch {
        // Error management here
    }

    return response.data
}

(async() => { // because "await" can only be used inside an async function. This is a little trick to make one

    const html = await fetchHTML('http://dummy.restapiexample.com/api/v1/employees');

    const $ = cheerio.load(html); // Cheerio is a server-side version of jQuery core. This loads the HTML text as a DOM, now you can access its HTML nodes with jQuery

    const restProto = $('#protocol');
    const apiToTest = $('#uri');
    const testApiResult = $('#output');

    console.log(restProto, apiToTest, testApiResult);
})

编辑: AAAAAH 我刚刚注意到您正在从 API 获取 JSON 数据,而不是 HTML 页面!

因此,您要做的是从获取的 JSON 中生成 HTML 页面!意义;您想将您从 API 收到的内容写入 HTML 页面!这就是“指导”页面的意思。所以这是不同的,你需要一个templating engine。例如;对于 Pug,它会是这样的:

myTemplate.pug

doctype html
html
    body
        h2 API Test (v 0.1 alpha)

        textarea#output
            | #{json}

        script(src="./apitest2.js")
        script(src="./apitest3.js")
        script(src="./responseDirector.js")

还有你的脚本:

const axios = require('axios').default;
const pug = require('pug');

const fetchJSON = async(url) => {
    const options = { url, timeout: 10000 };

    let response;

    try {
        response = await axios(options);
    } catch {
        // Error management here
    }

    return response.data
}

(async() => {

    const json = await fetchJSON('http://dummy.restapiexample.com/api/v1/employees');

    const html = pug.renderFile("myTemplate.pug", json); // Pass your data to Pug

    // Do what you want with your rendered HTML.
})

【讨论】:

  • 当我尝试运行您为答案提供的解决方案时(顺便谢谢!)我收到以下错误: import * ascheerio from 'cheerio'; ^^^^^^ SyntaxError: Cannot use import statement outside a module 有什么想法???
  • 此代码是否替换了我的 responseDirector.js 代码??
  • 我不知道 responseDirector.js 做了什么 :) 我只是在生成 HTML
  • 该文件旨在将节点脚本的输出推送到 HTML 页面。看起来不需要 responseDirector.js 脚本。你能告诉我如何使用你在答案中写的文件吗?我也需要更改html文件吗??
【解决方案2】:

我能够使用 parcelJS 解决问题。 它消除了对后端的需求,我可以将输出显示到包裹生成的 html 页面。

包裹详情here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多