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!');
});
Related
i am still new in node js, and i am trying to make some backend with file upload/ image upload function that can be stored in sql, i am trying using multer but it cant read my file while testing in postman body. anybody can help me where i do wrong?
here is my controller
const { db } = require('./db');
const bodyParser = require('body-parser');
const getgambar = (req, res) => {
const sqlQuery = "SELECT * FROM gambar";
db.query(sqlQuery, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
console.log(result);
}
});
};
const addgambar = (req,res) => {
const idimg = req.body.idimg;
const gambar = req.file.gambar;
console.log()
const sqlQuery = "INSERT INTO image (idimg,gambar) VALUE (?,?)";
db.query(sqlQuery, [idimg,gambar], (err, result) => {
if (err) {
res.send({
message: "error",
err
})
} else {
res.send({
message: "YES"
})
}
});
};
module.exports = {
getgambar,
addgambar,
};
here is my route
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const ctrl = require('./gambarctrl');
const storange = multer.diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storange: storange
})
router.get('/image/display', ctrl.getgambar)
router.post('/image',upload.single('gambar'), ctrl.addgambar)
module.exports = router;
and here my index
const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express();
const fileUpload = require('express-fileupload');
const gambarroute = require ('./gambarroute');
const multer = require('multer');
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(gambarroute);
app.listen(3000, () => {
console.log('on port 3000!');
});
i am still quite new in node js and i am still searching for tutorial, i appriciate for the help.
Two problems here...
Multer puts the single uploaded file into req.file so you should use
const gambar = req.file; // no `.gambar`
Assuming your DB column is a BLOB or BINARY type, you need to provide a Buffer.
Since you're storing the images within the DB, you don't need to use DiskStorage. Use MemoryStorage instead which provides a Buffer out-of-the-box
const upload = multer({
storage: multer.memoryStorage(), // watch your spelling
})
Then bind the .buffer property in your query.
db.query(sqlQuery, [idimg, gambar.buffer], (err, result) => {
// ...
});
To respond with the image from Express, use something like this
router.get("/image/display/:id", (req, res, next) => {
db.query(
"SELECT `gambar` FROM `image` WHERE `idimg` = ?",
[req.params.id],
(err, results) => {
if (err) {
return next(err);
}
if (!results.length) {
return res.sendStatus(404);
}
// set the appropriate content type
res.set("Content-Type", "image/jpg");
res.send(results[0].gambar);
}
);
});
and from the frontend...
<img src="http://localhost:3000/image/display/some-id" />
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'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.
I'm working on a project right now, i need to create a qrcode that contains a specific information in NodeJS. I have started by creating the canvas in HTML, and take it in NodeJS
<canvas id="canvas" width="300" height="300"></canvas>
And then in my NodeJS file, i'm launching my function
const fs = require('fs');
const qrcode = require('qrcode');
module.exports = {
generateQr: function(link){
var canvas = new qrcode(document.getElementById('canvas'));
qrcode.toCanvas(canvas, link, function (error) {
if (error) console.error(error)
console.log('success!');
});
}
};
Unfortunately, i got the error :
ReferenceError: document is not defined
From the above code, does it look correct ? Does the Qrcode get the data i'm passing, and then what should i do so the QR-code appear in my HTML ?
Thank you for your help
document is a browser-specific global object, you can't access it in node
In node environment, you could generate an image with QR code and use it.
Example:
Async/Await style:
const fs = require('fs');
const qrcode = require('qrcode');
module.exports = {
generateQr: async link => {
const qrCodeDataUrl = await qrcode.toDataURL(link);
// ...
}
};
Promise style:
const fs = require('fs');
const qrcode = require('qrcode');
module.exports = {
generateQr: link => {
qrcode.toDataURL(link)
.then(data => {
const qrCodeDataUrl = data;
// ...
})
.catch(err => {
console.error(error);
// ...
});
}
};
Callback style:
const fs = require('fs');
const qrcode = require('qrcode');
module.exports = {
generateQr: link => {
qrcode.toDataURL(link, function(err, data) {
if (error) console.error(error);
const qrCodeDataUrl = data;
// ...
});
}
};
To render it in an HTML-file you could use template-engine of your choice:
Example with ejs:
const ejs = require('ejs');
// In some route
const qrCodeDataUrl = await generateQr('some link');
const html = ejs.render('<img src="<%= qrCodeDataUrl %>" />', {qrCodeDataUrl});
res.header('Content-Type', 'text/html');
res.send(html);
// ...
Note: It's a simplified example. Please check ejs docs for more details
I am using it with node and mysql with angular 5.
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './assets/images/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
const fileFilter = (req, file, cb)=>{
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
cb(null, true);
}
else{
cb(null, false);
}
};
upload = multer({
storage: storage,
limits:{
filesize : 1024 * 1024 * 5
},
fileFilter : fileFilter
});
const app = express();
//DATABASE CONNECTION
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password: 'root',
database: 'inpblog',
port: 8889
});
// ALLOW CROSS ORIGIN
const corsOptions = {
origin: 'http://localhost:4200',
origin1: 'http://localhost:4202',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use('./assets/images', express.static(path.join(__dirname, 'dist', 'upload')));
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
connection.connect(function(error){
if(!!error){
console.log("error - db not connected");
}
else{
console.log("connected");
}
});
Here i define the code to upload a image in mysql database. through postman its upload a image in destination folder with multer middleware but when i upload a image through ng form its showing error in console."image undefined" and submit the "c:/fakepath/image.jgg" in mysql.
Here is the API to insert the post
app.post('/insertPost', upload.single('txt_blog_image'), jsonParser, (req, res) => {
console.log("image: ", req.file); // working fine only with postman
//console.log("rBody: ", req.body.txt_blog_image); // working fine only with Angular
let blogFields = {
post_author : req.body.txt_blog_author,
post_image : req.body.txt_blog_image
};
let sql = 'INSERT INTO insdb SET ?';
let query = connection.query(sql, blogFields, (err,result)=> {
res.send('New Post added...');
});
});
// Get All Post
app.get('/getallposts', (req, res) => {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.listen(4202);
Try this way.
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './assets/images/')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
In your api :
app.post('/getallposts',upload.single("image") , function(req, res) {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
})
From Angular side :
let form = new FormData();
form.append('image' , file);
Then console in server side , req.files to check file is coming or not ?
For more information and example please see this link