Using Node, express and axios to pull an API, want to send the resultant string to my index.html but having issues. Either overwrites my page and only shows the string or I can't access my variable.
server.js
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 3001;
app.use(express.static('public'));
app.get('/', async (req, res) => {
try {
const response = await axios.get('https://api.chucknorris.io/jokes/random');
console.log(response.data.value);
let quote = response.data.value;
res.send('index', quote);
} catch (error) {
console.error(error);
}
});
app.listen(PORT, () => {
console.log(`Server listening on: http://localhost: ${PORT}`);
});
index.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<p>
<!-- How to access "quote" here so I can format it how I want -->
</p>
<script src="assets/js/script.js"></script>
</body>
</html>
Getting the correct data just unable to format it. Any suggestions appreciated.
CodePudding user response:
Instead of using a static index.html
, create it in a function such as htmlTemplate
:
function htmlTemplate(quote) {
return `
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<p>
${quote}
</p>
<script src="assets/js/script.js"></script>
</body>
</html>
`
}
Then in call it the response
// …
const quote = response.data.value;
res.send(htmlTemplate(quote));
If you need to use a static HTML, add some unique-replaceable token in it. When reading it on the server, search and replace, e.g.: myHtml.replace('__QUOTE__', quote)
Security-wise, only do this if you trust the external API response. In other words, they are going to be able to inject anything they want in your site.