My index.html page
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Home</title>
</head>
<body>
<a href="./login.html">Please Login Here!</a>
</body>
</html>
My login.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example of Login Form</title>
</head>
<body>
<form action="login.html" method="post">
Username:<br>
<input type="text" name="username" placeholder="Username" required><br><br>
Password:<br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="login">
</form>
</body>
</html>
My server page
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}))
app.get('/',(req,res)=>{
res.sendFile(__dirname '/static/index.html');
})
app.get('/login',(req,res)=>{
res.sendFile(__dirname "/static/" "login.html");
})
app.post('/login',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
res.send(`Username : ${username} Password: ${password}`)
})
const port = 3000;
app.listen(port,()=>console.log(`This app is listening on port : ${port}`));
I am new to node.js.When I run using node server.js, I get Cannot GET /login.html.I can get into index.html. Why I am getting this. This is my directory
. ├── package.json . ├── server.js . └── static . . ├── index.html . . └── login.html
CodePudding user response:
try using express.static() middleware.
you can read more about serving static files here
ex:
const express = require('express');
const path=require('path');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'static')));//use folder containing your html files
app.get('/',(req,res)=>{
res.sendFile('static/index.html');
})
app.get('/login',(req,res)=>{
res.sendFile("static/login.html");
})
app.post('/login',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
res.send(`Username : ${username} Password: ${password}`)
})
const port = 3000;
app.listen(port,()=>console.log(`This app is listening on port : ${port}`));
CodePudding user response:
It appears that your request is to
/login.html
but there is no such route set up in your server.
There is a route
/login
which sends the file login.html
, so, to hit that route, it would be a url that looks like:
http://localhost:3000/login
NOT
http://localhost:3000/login.html
Alternatively, set up static
middleware to serve static files from a specified directory.