I was doing a nodejs based project using express and when I was adding partials to the server.js file. I got a type error: TypeError: hbs is not a function. I installed npm express-handlebars But still the same error
const express = require('express')
const http = require('http')
const path = require('path')
const hbs = require('express-handlebars')
const socket = require('socket.io')
const router = require('./routes/routes.js')
const app = express()
const server = http.createServer(app)
const session = require('express-session')
app.engine('hbs', hbs.express4({
defaultLayout: path.join(__dirname, 'views', 'layouts', 'default')
}))
app.use(express.json())
app.set('view engine', 'hbs')
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', require('./routes/home'))
app.set('views', path.join(__dirname, 'views'))
server.listen(PORT, () => { console.log(`Server is running at http://localhost:${server.address().port}`) })
Related
I'm trying to make a form that submits data, but the data when handled using express in the app.js file returns an empty array.
App.JS:
const mongoose = require('mongoose');
const express = require('express')
const path = require('path')
const Person = require('./models/Person')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.post('/post', (req, res) => {
const newInfo = req.body
console.log("Logging new data")
console.log(newInfo.emailAddress)
res.render('post')
})
On my home page i have a student login button. On clicking i want to redirect to a login page. But i am not getting request inside login route.
server.js file
const express=require('express');
const path=require('path');
const bodyparser=require('body-parser');
const session=require('express-session');
const{v4:uuidv4}=require('uuid');
const router=require('./router');
const app=express();
const port=process.env.PORT||3000;
app.arguments(bodyparser.json())
app.arguments(bodyparser.urlencoded({extended:true}))
app.set('view engine','ejs');
app.arguments(session({
secret:uuidv4(),
resave: false,
saveUninitialized: true
}));
app.use('/route',router)
//home route
app.get('/',(req,res)=>{
res.render('home');
})
app.listen(port,()=>{console.log("Listening to the server on http://localhost:3000")});
router.js file
var express=require('express');
var router=express.Router();
//student login page
router.get("/studentlogin",(req,res)=>{
res.end("Login Successfull");
})
Module.exports=router;
views/home.ejs file
<form action="/route/studentlogin">
<input type="submit" class="btn btn-outline-primary align-items-end" value="Student Login">
</form>
What i am expecting is to print login successfull but i am getting error.
Error
Cannot GET /route/studentlogin
Try to use app.use instead of app.arguments
Replace bodyParser with express
Add the cors library to enable CORS
Export a module using module.exports
Server.js
const express = require('express');
const path = require('path');
const cors = require('cors')
const session = require('express-session');
const { v4: uuidv4 } = require('uuid');
const router = require('./router');
const app = express();
const port = process.env.PORT || 3000;
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(
session({
secret: uuidv4(),
resave: false,
saveUninitialized: true,
})
);
app.use('/route', router);
//home route
app.get('/', (req, res) => {
res.render('home');
});
app.listen(port, () => {
console.log('Listening to the server on http://localhost:3000');
});
router.js
...
module.exports=router;
express js the body undefined error
I shared the files below. I got very angry. No error appears. Please help me.
Although I do it again I get the same error
I searched a lot but none of the solutions worked.
main.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
res.render('site/index')
})
router.get('/login', (req,res)=>{
res.render('site/login')
})
router.get('/register', (req,res)=>{
res.render('site/register')
})
router.get('/postcreate', (req,res)=>{
res.render('site/postcreatepage')
})
router.get('/postupdate', (req,res)=>{
res.render('site/postupdatepage')
})
router.post('/post/post', (req,res)=>{
console.log(req.body)
})
module.exports = router
I checked and searched many times could not solve
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
app.use('/', main)
app.use(express.static('static'))
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.listen(port, hostname, ()=> console.log(`Example app listening on port http://${hostname}:${port}/`))
Although I do it again I get the same error
html
<html>
<head>
</head>
<body>
<form action="post/post" method="post">
<input name="title"><br>
<input name="content"><br>
<button type="submit">But</button>
</form>
</body>
</html>
In your route, you have to return a response other wise the request will hang:
main.js
router.post('/post/post', (req,res)=>{
console.log(req.body)
const resObject = {
... do something with req.body ...
};
return res.status(201).json(resObject);
});
In your app entrypoint, set your routes after your config and middleware:
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
/* config */
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
/* Middleware */
app.use(express.static('static'))
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/* Routes */
app.use('/', main)
app.listen(port, hostname, () => console.log(`Example app listening on port http://${hostname}:${port}/`)
I get next error when trying open http://localhost:5000/
Error:
ENOENT: no such file or directory, stat
'C:\Users\Andriixyz\Desktop\chat- node\chat\client\build\index.html'
const path = require("path");
const port = process.env.PORT || 5000;
const express = require("express");
const app = express();
const server = app.listen(port);
var io = require("socket.io").listen(server);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("client"));
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
});
[app.js]
onCreate = async (event) => {
event.preventDefault();
const clubData = new FormData(event.target)
console.log(clubData);
const post = await axios.post('/club', {
method: 'POST',
body: {
name : 'name',
intro : 'intro'
}
}).then(response => {console.log(post)})
}
This is when the router is not division.
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
At this point, we were able to see data coming over from the developer window at Chrome.
However, after splitting the router, an error occurs.
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
var clubRouter = require('./router/clubRouter.js');
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use('/club', clubRouter);
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
[clubRouter.js]
const router = require('express').Router();
const controller = require('../controller/clubController');
router.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
module.exports = router;
An error occurs at this time.
(POST http://localhost:3000/club 404 (Not Found))
I've now created a project with a react-app-create and webpack.config.Added the code to dev.js file.
devServer: {
port: 4000,
open: true,
proxy: {
"/": "http://localhost"
}
},
The code was also added to the package.json file .
"proxy": "http://localhost:4000"
The clubRouter is mounted on path /club
That means any /club* requests will be handled over to clubRouter
The clubRouter further registers a controller on path /club that sends the response { test: 'test'}
So,
The complete path would now be => /club/club
In your React app, try this change and it would work:
const post = await axios.post('/club/club', { ... })
If you think the path is not how you want, you can register the controller in the clubRouter as follows:
router.post('/', function(req, res, next) {
res.send({ test: 'test'});
})
That way, you would be able to get hit it with the old path as:
const post = await axios.post('/club', { ... })