can I just upload some on file with Expressjs with bodyParser.json() middleware? I'm using Expressjs 4.14 and my app.js snipet is like this
require('dotenv').config();
require('./app/models/db');
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var socket_io = require("socket.io");
var io = socket_io();
app.io = io;
var mainRouteConfig = require('./app/routes/routes')(io);
// var notifRouteConfig = require('./app/routes/notif')(io);
// view engine setup
app.set('views', path.join(__dirname, 'app', 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({ secret: 'super-secret-code'}));
app.use('/', mainRouteConfig);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// io.on("connection", function(socket){
// console.log( "A user connected" );
// });
module.exports = app;
I think the problem is in app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); when want upload some file using multipart/form-data
BodyParser is mainly used for urlencoded enctype.
For multipart I use Formidable and express-formidable.
npm install formidable express-formidable --save
Take a look at docs here
Good luck
Related
I will try to describe my question well and what I trying to archieve
I have lots of table like this in my nodejs app
everying member I will give it a href to "/profile/"theirUsername""
after watching ton of tutorial,
I add a button href to my username
$('#pendingDepositTable').append(`
<tr>
<td>
<div class="d-flex align-items-center">
<div class="table-user-name ml-3">
<p class="mb-0 font-weight-medium">`+ response[i].id + `</p>
</div>
</div>
</td>
<td>
<a href="/profile/`+ response[i].customer + `">
`+ response[i].customer + `
</a>
</td>
<td>`+ response[i].bank + `</td>
<td>`+ response[i].amount + `</td>
<td>
<div class="badge badge-inverse-warning"> `+ response[i].status + ` </div>
</td>
<td>`+ response[i].date + `</td>
<td>
<i class="mdi mdi mdi-check-all"></i>
<i class="mdi mdi-close"></i>
</td>
</tr>
`)
}
I add this in my profile.js
router.get('/:id', function (req, res, next) {
console.log(req.params.id);
db.query("SELECT * FROM `customers` WHERE `username` = '" + req.params.id + "'", function (err, result, field) {
try {
res.render('templateMember', { customers_profile: result });
} catch (error) {
console.log(error)
}
})
Before I render the page, I use res.send(result) and get the data that I want successfully.
But all of my header and js script all messed up (I put these in partials.)
and the url all gone wrong
example my transaction page is http://localhost:3000/deposit
but if i redirect from here it become http://localhost:3000/profile/deposit
What can I do or if i miss something?
my projects folder
my app.js
var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('express-flash');
app.use(flash());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
var indexRouter = require('./routes/index');
var loginRouter = require('./routes/user_signin');
var memberRouter = require('./routes/members');
var depositRouter = require('./routes/deposit');
var withdrawalRouter = require('./routes/withdrawal');
var creditTransferRouter = require('./routes/creditTransfer');
var cashBonusRouter = require('./routes/cashBonus');
var productListingRouter = require('./routes/products_listing');
var productBalanceRouter = require('./routes/products_balance');
var bankListingRouter = require('./routes/banks_listing');
var bankBalanceRouter = require('./routes/banks_balance');
var bonusRouter = require('./routes/bonus');
var profileRouter = require('./routes/profile')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Login API
app.use('/auth', require('./routes/controllerRoute/auth'));
// Post Product API
app.use('/product_add_action', require('./routes/controllerRoute/product_add_action'));
// Add Member API
app.use('/addMemberRouter', require('./routes/controllerRoute/addMemberRouter'));
app.use('/', indexRouter);
app.use('/userSignin', loginRouter);
app.use('/member', memberRouter);
app.use('/deposit', depositRouter);
app.use('/withdrawal', withdrawalRouter);
app.use('/credittransfer', creditTransferRouter);
app.use('/cashbonus', cashBonusRouter);
app.use('/products_listing', productListingRouter);
app.use('/products_balance', productBalanceRouter);
app.use('/banks_listing', bankListingRouter);
app.use('/banks_balance', bankBalanceRouter);
app.use('/profile', profileRouter);
app.use('/bonus', bonusRouter);
app.all('/', function(req, res){
console.log(req.session)
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Sorry I just found out the answer.
instead of using src="xxx.css"
it should be src="/xxx.css" The leading slash indicates that the request is relative to root not the path that is making the request.
Sorry for post the question without reviewing my code carefully.
I have tried to search for an answer here but nothing so far worked, not many threads about handlebars.
I am struggling to get images to show up on my node app.
I have this on app.js and below that the code i am trying to get image to show up on the .hbs file:
const express = require("express");
const path = require("path");
const hbs = require("hbs");
const app = express();
const bodyParser = require("body-parser");
const port = process.env.PORT || 80;
require("./db/conn");
const SwimmingCollection = require("./models/schema");
const static_path = path.join(__dirname, "../public");
const template_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.use(express.static(static_path));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "hbs");
app.set("views", template_path);
hbs.registerPartials(partials_path);
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`Listening to the port at ${port}`);
});
How to fix this issue?
Try below line for Static Path.
app.use(express.static(path.join(__dirname, 'public')))
https://expressjs.com/en/starter/static-files.html
So i have a website that runs on express with some MySQL queries to load photo albums.
The problem is that when i go to /photo everything works fine but if I refresh the page then i get a 404 NOT FOUND. Same if i go first to /photo then on another url and back to /photo.
The problem happens regardless if it's in prod or dev but only happens on my server, never on local.
here's what i get :
NotFoundError: Not Found
at /home/vincdgfq/sachalebas/app.js:53:7
at Layer.handle [as handle_request] (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:317:13)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:335:12)
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:275:10)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:635:15
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:174:3)
at router (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:47:12)
If i remove all my error handlers i just get a
CANNOT GET /501.shtml
website can be found here : https://sachalebas.com/photo
Thanks in advance if anyone has got any idea where i should look for with this error i'm totally lost.
EDIT:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
require('./controllers/userController');
const oneYear = 60 * 1000 * 60 * 24 * 7;
const xssFilter = require('x-xss-protection');
const noSniff = require('dont-sniff-mimetype');
require('dotenv').config({ path:"process.env"});
const compression = require('compression');
var indexRouter = require('./routes/index');
var app = express();
app.use(xssFilter());
app.use(noSniff());
app.use(compression());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public', {maxAge: oneYear, dotfiles:'allow'}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
maxAge: 200000
}));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here's my app.js
Your issue not with backend.
I've done curl requests multiple times and I'm getting same output:
which means issue on clientside with race conditions.
to avoid it try to wrap all code: https://sachalebas.com/ressources/js/script.js
Inside of:
window.onload = function() {
// here goes all js code from ressources/js/script.js
}
or make sure You don't have blocking layer in css that being rendered before image.
I am trying to take some very simple text input through a form and direct it to a .txt file. not getting much luck and am way out of my depth, any help appreciated.
I have tried a few different ways but atm i am trying to GET the input, turn this into json data and send directly to the file.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
var passport = require('passport');
var passportLocal = require('passport-local');
var expressSession = require('express-session');
var expressValidator = require('express-validator')
//routes setup
var index = require('./routes/index');
var homepage = require('./routes/homepage');
var login = require('./routes/login');
var charitySignUp = require('./routes/charitySignUp');
var about = require('./routes/about');
var contactUs = require('./routes/contactUs');
var charityHomepage = require('./routes/charityHomepage');
var chat = require('./routes/newsFeed');
var ticket = require ('./routes/ticket');
var app = express();
require('./public/configure/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//app.use(session({secret: 'mySecret', resave: false, saveUninitialized:
false}));
//app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//routes + backend js file
app.use('/', index);
app.use('/login', login);
app.use('/homepage', homepage);
app.use('/charitySignUp', charitySignUp);
app.use('/about', about);
app.use('/contactUs', contactUs);
app.use('/charityHomepage', charityHomepage);
app.use('/chat', chat);
app.use('/ticket', ticket);
/ catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Ticket.js - backend code
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function (req, res, next) {
res.render('ticket');
});
router.get('/insert', function (req, res) {
var issue = req.query.issue;
var email = req.query.email;
fs.appendFile("my_file.txt", JSON.stringify(email + issue), function (err) {
if (err) throw err;
console.log('updated');
});
});
module.exports = router;
form in .EJS file.
<form class="form-signin" action="/insert" method="get">
<h2 class ="text" class="form-signin-heading">Ticket form</h2>
<label class="sr-only"><b>email</b></label>
<input type="Email" class="form-control" placeholder="Enter email you would like your response directed" name="email" required>
<label class="sr-only"><b>Issue</b></label>
<input type="text" class="form-control" placeholder="type here" name="issue" required>
<button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</form>
I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});