I've an problem with evaluating an HTML Form using NodeJs and express.
This is my Java Script Code
My goal is to handle HTML Form in nodeJs using express.
const express = require('express');
const http = require('http');
const fs = require('fs');
const app = express();
var warehouses = [];
app.use(express.urlencoded({extended: true}));
app.use("/warehouse", (req, res, next) => {
fs.readFile("./addWarehouse.html", function(err, data) {
res.write(data);
next();
});
});
app.post("/warehouse/add", (req, res) => {
console.log("ADDED");
// warehouses.push(req.body.nWarehouse);
console.log('Request Type:', req.method);
res.end;
});
app.listen(8080);
And this is my HTML Form
<!DOCTYPE html>
<!-- <head>
<meta charset="utf-8" />
<title>Coole Seite</title>
</head> -->
<body>
<h1>Warehouses</h1>
<form method='POST' action="/warehouse/add">
<input type="text" name="nWarehouse" id="nWarehouse"/>
<input typse="submit" value="bitte sende" />
</form>
</body>
</html>
I tried to debug it with the console output and I figured out that it never access the app.use("/submit/add/" ... " part.
I would be happy to get some advice.
Here if the intent is to evaluate the form that is there in addWarehouse.html which should render when you go to /warehouse and the form should submit to /warehouse/add.
The middleware concept used via app.use(...) here is not required at all.
Express code:
const express = require('express');
const http = require('http');
const fs = require('fs');
const app = express();
var warehouses = [];
app.use(express.urlencoded({extended: true}));
//show addWareHouse.html for /warehouse
/* serving the HTML via fs */
app.get("/warehouse", (req, res, next) => {
fs.readFile("./addWarehouse.html", function(err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
//add warehouse form submit for /warehouse/add
app.post("/warehouse/add", (req, res) => {
console.log("ADDED");
console.log("REQUEST PARAM::", req.body);
//do you adding of ware-house stuff here
console.log("Request Type:", req.method);
return res.end();
});
app.listen(8080, () => console.log(`app listening on port 8080!`));
Note:
There are other handy ways to serve views (HTML) in express like template engines, res.sendFile() etc.
Related
I have been having trouble with displaying the API information that I fetched using node-fetch. I want the data title, img, and etc to show in the ejs body, but I receive an error message from index.ejs saying currentData is not defined.
var express = require('express');
var fetch = require('node-fetch');
var app = express();
//Port information
const port = process.env.port || 3000;
//tell application to use ejs for templates
app.set('view engine', 'ejs');
//make styles public
app.use(express.static("public"));
app.get('/', function(req,res){
//return something to homepage
res.render('index');
});
app.get('/comic', function(req,res){
let currentData;
fetch('http://xkcd.com/info.0.json')
.then(res => res.json())
.then(data => {
curentData = data;
res.json(currentData);
});
});
//index.ejs file:
<div>
<form action ="/dailyInfo" method="POST">
<%= currentData.month %>
</div>
Problem:
I quite confused to why my render is not loading my css and images from uploads.
When I do not try to log in, every page loads it's images and css applies it's styles..
But when I try to render my page like so:
if(!results.length){
res.status(401).render('home/login', {
message: 'The email or password is incorrect'
});
}
I get this error:
I realized it says ...:3000/auth/css/.. - it's not suppose to load auth?
This is my tree:
Index.js
|
├───controllers
├───helpers
│
├───public
│ ├───css
│ ├───javascript
│ └───uploads
├───routes
│ └───home
└───views
├───home
├───layouts
└───partials
└───home
index.js
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const app = express();
// Public path
app.use(express.static(path.join(__dirname, './public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Parse URL encoded bodies
app.use(express.urlencoded({ extended: false }));
//Parse JSON bodies as sent by API clients
app.use(express.json());
app.use(cookieParser());
// View engine
app.engine('handlebars', exphbs({defaultLayout: 'home-index'}));
app.set('view engine', 'handlebars');
// Routing
app.use('/', require('./routes/home/page_routes'));
app.use('/auth', require('./routes/auth'));
app.listen(3000, () => {
console.log('Listening');
});
views/layouts/home-index.handlebars
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/home.css">
<title></title>
</head>
<body>
{{> home/home-nav}}
{{{body}}}
</body>
</html>
routes/auth.js
const { db } = require('./db');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var { promisify } = require('util');
// Login
exports.login = async function(req, res) {
try {
var {email, password} = req.body;
if(!email || !password) {
return res.status(400).render('home/login', {
message: 'Please provide an email and password' ///////////////// This is the problem
});
}
db.query('select * from users_website where email = ?', [email], async function(error, results){
console.log(results)
if(!results.length){
res.status(401).render('home/login', {
message: 'The email or password is incorrect' ///////////////// This is the problem
});
}
else{
var id = results[0].id;
var token = jwt.sign({ id }, 'SuperSecretPassword9981998', {
expiresIn: '90d'
});
console.log("The token is: " + token);
var cookieOptions = {
expires: new Date(
Date.now() + 90 * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/");
}
});
} catch (e) {
console.log(e);
}
}
routes/home/page_routes
const express = require('express');
const router = express.Router();
const auth_controller = require('../../controllers/auth');
// Home router
router.get('/', auth_controller.isLoggedIn, (req, res) => {
res.render('home/index');
});
// Login
router.get('/login', (req, res) => {
res.render('home/login');
});
module.exports = router;
Question
How do I get rid of the error - when trying to render the page?
The reason for this is that you are loading assets using relative URLs in your handlebars file, which means that the assets are loaded relative to the page's URL, which, in your case, is :3000/auth. To fix this, use an absolute URL instead.
Like this:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Notice the leading slash. -->
<link rel="stylesheet" href="/css/home.css">
<title></title>
</head>
<body>
{{> home/home-nav}}
{{{body}}}
</body>
</html>
I am trying to upload a file from my page to node server.
I can see form data are arriving in the router on server.
But no file is saved in upload folder.
What am I doing wrong?
//router unit
const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log('chegei')
cb(null, "uploads/")
},
filename: (req, file, cb) => {
console.log('chegei2')
cb(null, Date.now() + "-" + file.ogirinalname)
},
});
module.exports = function (page) {
router.post('/SendMsgBase64', async (req, res) => {
var upload = multer({ storage: storage }).single('userFile');
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.send({ "data": "Error uploading file." });
}
return res.send({ "data": "File is uploaded" });
});
return router
}
//app.js unit
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const WARoutes = require('../routes/WARoutes');
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.sendFile('/index.html');
})
app.use('/whats', WARoutes(this.page));
//html
<form id="uploadForm">
<input type="file" name="userFile" />
<input type="button" value="Upload Image" onclick="uploadFile();">
<span id="status"></span>
</form>
<script>
uploadFile = () => {
var formData = new FormData();
debugger
var logoImg = $('input[name="userFile"]').get(0).files[0];
formData.append('logo', logoImg);
var objArr = [];
objArr.push({ "id": "123", "name": "luiz" });
//JSON obj
formData.append('objArr', JSON.stringify(objArr));
$.ajax({
url: "/whats/SendMsgBase64",
type: "POST",
processData: false,
contentType: "application/x-www-form-urlencoded",
data: formData,
complete: function (data) {
alert("success");
}
})
};
</script>
According to multer's github page, if you have not created the uploads directory, it may go something wrong.
If this is the case, creating the directory on your own or passing a string value to destination property is the solution for you.
https://github.com/expressjs/multer
Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.
I am trying to get my node js to return and output the value taken from a Html form.
The node.js file is as follows
const app = express();
var path = require('path');
var fs = require('fs');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
var myText = req.query.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));
The HTML is
<!DOCTYPE html>
<html>
<body>
<h1 style="color:Blue">Docker</h1>
<div id="floating-panel">
<form action="/myform" method="post">
<input type="text" name="mytext" required />
<input type ="submit" value="Submit">
</form>
</div>
</body>
</html>
when I fill out the form I get the Output "Your Text:undefined" , why isnt myText variable being updated?
req.query.mytext is wrong.
req.query use when you want to extract query string.
I think here you need to use req. body, Please replace your code with following code
const app = express();
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
const myText = req.body.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));
This is what you need to do:
index.js
var express = require('express');
const app = express();
var path = require('path');
var fs = require('fs');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
var myText = req.body.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));
I want to read an HTML file.
My HTML content:
<html>
<hear>
<title>Learn NodeJS</title>
</head>
<body>
<center>
<h1>Learn NodeJS with Khuong Pham</h1>
<img width="400" src="/nodejs.png" />
</center>
</body>
</html>
I've tried:
const http = require('http')
const fs = require('fs')
const express = require('express')
const app = express()
const folderPath = __dirname + '/public_files'
app.use(express.static(folderPath))
http.createServer(function(request, response) {
var filePath = folderPath + '/index.html'
console.log(filePath)
fs.access(filePath, fs.F_OK | fs.R_OK, function(err) {
if (err) {
response.writeHead(404, { 'Content-Type' : 'text/html' })
response.end('<h1>File not found</h1>')
} else {
fs.readFile(filePath, function(err, contentFile){
if (!err) {
response.writeHead(200, { 'Content-Type' : 'text/html' })
response.end(contentFile)
} else {
response.writeHead(500, { 'Content-Type' : 'text/html' })
response.end('<h1>Can not read this content</h1>')
}
})
}
})
}).listen(3500)
But when I access http://localhost:3500/, it says:
You are mixing two methods here. Firstly you are trying to use express, but later you are starting your own server using http.createServer Instead you should use express to do so.
Your js should be something similar to below. Have not tested below code. Edit it approiately. This is just to show the idea.
const http = require('http')
const fs = require('fs')
const express = require('express')
const app = express()
const folderPath = __dirname + '/public_files'
//mount your static paths
// renders your image and index.html
app.use(express.static(folderPath))
// renders your index.html
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
//mount your other paths
// in this case render 404.
app.get("*",function (req, res) {
res.status(404).send(''<h1>File not found</h1>'');
});
//start the server.
app.listen(3500, function () {
console.log('Example app listening on port 3500!');
});