I developed a website with html, css and Javascript and the backend was done with Node.JS. Is there a way i can link them together so that the sign up or login pages on the html takes the user to the backend interface done with Node.js without having to convert the frontend to React?
CodePudding user response:
Yes. React, as well as the client-server web architecture itself, works with HTTP interactions. If it's your first time working with HTTP calls between client and server, I would personally suggest you to start with a client/library that simplifies API interactions like Axios (https://axios-http.com/docs/intro) for your front-end. But obviously, JavaScript running in a browser contains functions to intearct with external APIs by default, see for example this usage of the fetch
JS function:
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
Source: HTTP GET request in JavaScript?
More information on the docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
This has a lot of theory and things to study behind, is nearly impossible to answer this question as a one-shot. Sorry.
CodePudding user response:
If your backend is done using Express.js, then you can add a public folder to your root folder and include your HTML, CSS and Javascript in there. For example:
project root
├── server.js
├── package.json
└── public
├── CSS
├── img
├── scripts
└── style.css
├── views
└── index.html
The views directory will have your templates First, serve the static files using:
app.use(express.static('public'))
Then now, you can link your files to your backend entry file using a relative path. To do that, just import the path module on your server/ entry file:
const path = require('path')
Then you can use it as:
app.use('/img', express.static(path.join(__dirname, 'public/img')))
app.use('/css', express.static(__dirname 'public/css'))
Set views:
// Set View's
app.set('views', './views');
app.set('view engine', 'html');
To add a page:
app.get('/about', (req, res) => {
res.sendFile(__dirname '/views/about.html')
})
Listen to port:
app.listen(port, () => console.info(`App listening on port ${port}`))
Hope this helps!