I am new to node js, I have my index.html and app.js
My Index.html
<!DOCTYPE html>
<html>
<!-- \\ Bootstrap CDN -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p" crossorigin="anonymous"></script>
<body>
<style>
.input-group{
padding: 30px;
}
#button{
margin-left: 30px;
}
</style>
<form action="/users" method="get" >
<div class="input-group">
<span class="input-group-text">First and last name</span>
<input type="text" name="name" class="form-control">
<input type="text" aria-label="Last_name" class="form-control">
<input type="submit" class="btn btn-primary" id="button">
</div>
</form>
</body>
</html>
my app.js
//For users page route
const express = require('express')
const app = express()
app.get('/users',(req,res)=>{
res.send("data page")
console.log("data page")
})
// FOR THE HTML PAGE
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
server.listen(process.env.PORT || 3000)
when I run the app.js file, it's not logging "data page" when I click submit button from my index.html, need help, am not sure am routing it properly.
CodePudding user response:
It is not necessary to use the HTTP module with express also you have not started your express app.
if you want to send an HTML file in the express (assuming the HTML file is in the same directory).
const express = require('express')
const app = express()
app.get('/',(req,res)=>{
res.sendFile('index.html',{root: __dirname });
});
app.get('/users',(req,res)=>{
res.send("data page")
console.log("data page")
})
app.listen(process.env.PORT || 3000);
If you want to use streams you can follow Rahul's Answer
If you still want to use the HTTP module with express you can read this post. Why combine http module with express module
CodePudding user response:
Change your app.js code to
const fs = require('fs')
const express = require('express')
const app = express()
app.get('/', (req, res) => {
// for html page
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
app.get('/users', (req, res) => {
res.send("data page")
console.log("data page")
})
app.listen(process.env.PORT || 3000)
In your current app.js file there is a routing issue as all the route will render the index.html page