javierdemartin
javierdemartin

Reputation: 645

Passing parameters from Node.JS to HTML file

I am parsing an array from an API in Node and then handling it to my HTML file so I can draw on a map some points I received from the API. I want to pass as a parameter the array so the HTML receives it. I've looked through all the other possible answers here but none worked.

index.js

const express = require('express')
const util = require('util')
var request = require("request")

var path = require('path')

const app = express()

app.get('/_bicis', (req, res) => {

    var url = "https://nextbike.net/maps/nextbike-official.json?city=532"

    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            data = body['countries'][0]['cities'][0]['places']

            res.sendFile(path.join(__dirname + '/index.html'), {data: data});
        }
    })
})


module.exports = app

index.html file

<html><head>
</head>
<body>
<script>

    // When printing this line it raises an error
    console.log("RECEIVED FROM HTML" + data)
</script>
</body></html>

I am not using any template to generate my HTML file, should I? Can it be done with the code I have?

Upvotes: 0

Views: 1287

Answers (1)

Carsten
Carsten

Reputation: 943

This will not work because data is only available in your Node.js environment and not inside your browser. In this case, express is only used to serve the static HTML file index.html. In your browser environment, the data is no longer available.

There are two methods to pass the data to your browser:

  1. Use a template to generate your HTML code on the server side.
  2. Move the API request to a different route, like app.get('/_bicis/api', ...) and use a front-end framework to make an AJAX call to the new route. This will request the data from your browser and you can use front-end JavaScript to build your HTML.

Upvotes: 1

Related Questions