I am building my server and client using node express.
I want my HTML file first(Which is done by express static automatically) then JSON file next so that JSON data is displayed on my html file well.
This is my file structure
- index.js
- public
|
- index.html
|
- front-end.js
index.js
const express = require('express');
const app = express();
const names = {...}
app.use(express.static('./public'));
app.get('/', (req, res) => {
return res.json({names});
})
front-end.js
axios.get('/')
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err);
})
index.html
<html>
...
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="front-end.js"></script>
</html>
But JSON data transferring part is not working. the only res
I can get in axios
is index.html file. It is done internally by express with static
.
I looked through the document about express static options but found no clues yet.
Isn't there any other way that I can do while leaving express.static
part? or Do I need to change the part?
CodePudding user response:
A client (like a browser) makes an HTTP request. It then gets an HTTP response. A single HTTP response. You can't send multiple responses to a single request.
In this case, the browser makes a request for /
and Express checks each route in turn until it finds a match. Since you have an index.html
file in the directory you configured with static
against /
it serves that and never reaches app.get('/'
.
That said, I have no idea what behaviour you expect from a single URL serving up both an HTML document and a JSON text. They are fundamentally very different things that get handled in very different ways.
Perhaps you want to make the data in the JSON text available to JavaScript running in the HTML document.
In that case:
- give the endpoint handling the JSON a different path
- use Ajax (e.g. with the axios library that you've loaded) to request that URL
- use DOM manipulation to add the data to the document