简体   繁体   中英

Importing node.js require modules to .html

I am working on a complex program which involves uploading an excel sheet, creating a table and then work with the data in the table.

I must read first column of all rows and for every string, I must perform API call to the server.

The API request is performed as following:

async function main()
{
    var id = await GOR_login();
    console.log(id)
    var result = await Gor_completed_actions(id,"RUT240");
    console.log("emmiting result123=",result)
    
}

I used async and await functions to ensure that I get the result before I pass it to another function. For example GOR_login() is going to perform API GET request and if I do not use away, the data in console.log(id) will be undefined. I am not sure whether that is a correct way of doing.

Both API request functions GOR_login() and Gor_completed_actions are using node.js module fetch-node. I would like to call these functions in my html file after my table is being created, but I must somehow import fetch-node module to the html file.

Please check this JS fiddle: http://jsfiddle.net/v04k3w7j/ .

After uploading the excel document, it will create a table and fill the array codes_to_updt []. This array tells me what API calls I need to make. After that, I must execute the function for the API calls:

async function main()
{
    var id = await GOR_login();
    console.log(id)

    var result = await Gor_completed_actions(id,codes_to_updt); // call with codes_to_updt one by one
    console.log("emmiting result123=",result)

}

The issue for me that I am not able to use fetch methods in.html file. In my.js file I do:

var fetch = require("node-fetch");

But it does not allow me to do that in.html.

Can someone clarify me what is the best solution to this problem?

UPDATE1 I hide the URL just for security reasons

Inside my.html, I try to use the following function for my html get request:

function httpGetAsync(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

And then this function is being called after the my array is filled:

    httpGetAsync(URL_start_session);

The error is returned:

Access to XMLHttpRequest at 'my_url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Trying to upload and parse the excel on node(server) side.

I have downloaded an xlsx module and with the following code, I am able to parse the excel document:

var XLSX = require('xlsx')
var workbook = XLSX.readFile('gor_plan2.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);

The console.log output returns me data:

[
  { Produkto_kodas: 'Product1', Kiekis: 50 },
  { Produkto_kodas: 'Product2', Kiekis: 295 },
  { Produkto_kodas: 'Product3', Kiekis: 244 },
  { Produkto_kodas: 'Product4', Kiekis: 225 },
  { Produkto_kodas: 'Product5', Kiekis: 17 }
]

Now I try to build a table out of this data.

How can I convert the JSON object data xlData into something html like:

    <tbody>
        <tr>
            <th>Produkto kodas</th>
            <th>Kiekis</th>
        </tr>
        <tr>
            <td>Product1</td>
            <td>50</td>
            </tr>
            <tr>
            <td>Product2</td>
            <td>295</td>
            </tr>
            <tr>
            <td>Product3</td>
            <td>244</td>
            </tr>
            <tr>
            <td>Product4</td>
            <td>225</td>
            </tr>
            <tr>
            <td>Product5</td>
            <td>17</td>
            </tr>
            </tbody>
            </table>

I think you can't import Node modules on PureJS. But you can try calling a NodeJS function like this:

Note: I'm using express.js, hope this is not a problem for you.

//index.js
const expressjs = require("express")
const app = expressjs();

app.set('view engine', 'html');
app.set('views', __dirname + '/views');

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

function func() {
   var XLSX = require("xlsx")
}

app.listen(port, () => {
   console.log("Listening")
}

HTML Server-Side:

<script>
    var url = "http://ip:port/resources"
        async function nodecall() {
            fetch(url)
        }
</script>
<button id="tap" onclick="nodecall()">Call NodeJS</button>

If you want to pass a variable from server-side to client-side you can do something like this:

NodeJs:

app.get("/resources", (req, res) => {
   var variable = req.query.var
   var variable2 = req.query.var2
});

HTML:

var url = "http://ip:port/resources?var=hello&var2=world"

And if you want to do the opposite. Client to Server...

NodeJs:

app.get("/resources", (req, res) => {
   var string = "Hello World"
   return res.send(string)
});

HTML:

let variable = await(await fetch(url)).text()

Remember to put HTML files in a folder named "views".

You can combine all of them if you want to. Hope this helped. Bye!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM