0

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?

3
  • "I am not using any template to generate my HTML file, should I?" — Yes. That is what templates are for. Commented May 16, 2019 at 11:35
  • "When printing this line it raises an error" - what is the error? Commented May 16, 2019 at 11:41
  • 1
    @mrdeadsven — It'll be a reference error because data isn't declared in that program. Commented May 16, 2019 at 11:52

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.