Reputation: 982
I'm currently trying to figure out nodejs and express.
At the Moment I have a small sample project running on my local machine.
When accessing /login I want to be redirected to the login.html file.
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, '/login/login.html'));
})
does the job quiet nicely.
I had the css directly in the header and now I'd like to access a shared folder from the html site itself.
File Structure:
- project
+--- node_modules
+--- package.json
+--- index.js
+--- shared/
+--- css/
+--- style.css
+--- images/
+--- login/
+--- login.js
+--- login.html
I found the following solution in the express docs: https://expressjs.com/en/starter/static-files.html and it's - at least what I think - what I need.
currently I'm only using index.js and login.js
how do I actually use the provided static files? Am I supposed to provide them in the index.js?
index.js:
const express = require('express');
var path = require('path');
const cors = require('cors');
const port = process.env.PORT || 3000;
const app = express();
app.use(cors());
app.use('/static', express.static(path.join(__dirname + './static')));
app.get('/', async (req, res) => {
res.send('hello world!');
})
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, '/login/login.html'));
})
app.listen(port, () => {
console.log('listening on http://localhost:' + port);
})
login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="shared/css/style.css">
</head>
<body>
<div class="login-form">
<h1>Login Form</h1>
<form action="auth" method="POST">
<input autocomplete="off" type="text" name="username" placeholder="Username" required>
<input autocomplete="off" type="password" name="password" placeholder="Password" required>
<input type="submit">
</form>
</div>
</body>
</html>
Upvotes: 0
Views: 1512
Reputation: 954
You need to change your static path to and allow express to serve static file
//here login is the folder name which contain index.html file so you need to define that path
var public = path.join(__dirname, 'login');
app.use(express.static(public));
app.get('/login', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
Upvotes: 1