0

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> 

1 Answer 1

1

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

1 Comment

thank you very much! I adapted it and put it directly into the index.js of the app to provide the public file everywhere (for testing)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.