I am trying to upload a single image using python code to a node js express server. The python code is:
import requests
url = 'http://localhost:9000/testAPI/uploadphoto'
files = {'file': ('photo', open('test.jpg', 'rb'))}
ret = requests.post(url, files=files)
print ret
For the app.js, it is mostly following the default template:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser= require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// 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;
and I am using the router testAPI for handling the POST:
var express = require('express');
var multer = require('multer');
var router = express.Router();
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
cb(null, Date.now() + "_" + filename);
}
});
var upload = multer({ storage: storage });
router.get('/', function(req, res, next) {
console.log("test");
res.send('API is working properly');
});
router.post('/uploadphoto', upload.single('photo', (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send('Photo uploaded');
}));
module.exports = router;
When I run the python code, the server returns 500. In my node js directory, I have an uploads folder created.
At the first you should run your node server project in port 9000
Your npm start probably calls your bin/www file. Which contains the listen invocation to start your app.
Many people set up their app this way. eg. app.js to define and configure their app, and something like bin/www to actual get the server running. This way they can include the app.js into other parts, say tests, without actually starting the server when you require it.
Figured it out. Since my server is started in the bin/www file as opposed to the app.js file, from the terminal I went into my bin directory and then called
node wwww
or
nodemon www
or add this code to the app.js and then run it with node app.js to listen port 9000
const port = 9000;
app.listen(port, () => console.log(Example app listening on port ${port}!))
Related
I've got a basic Node JS app (as I'm just learning). I'm using express, express-generator, express-myconnection, and mysql.
The issue has to do with querying the database connection itself.
The app is designed using an MVC structure.
Edit: to start off, here is my "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 index = require('./routes/index');
//var users = require('./routes/users');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
app.use(
connection(mysql,{
"host":"localhost",
"user":"root",
"password":"root",
"port":3306,
"database":"fruits"
},'request')
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// 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;
I have a model file, "fruits.js":
var fruits = function(data, req){
this.data = data;
this.req = req;
}
fruits.prototype.data = {};
fruits.prototype.getAll = function(callback){
this.req.getConnection(function(err, connection){
console.log(connection);
//var q = connection.query("SELECT * FROM `fruits`", function(err, rows){
//callback(rows);
//});
});
};
module.exports = fruits;
Then I also have a controller file (index.js):
var express = require('express');
var router = express.Router();
var fruits = require('../models/fruits.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*GET fruits page */
router.get('/fruits',function(req, res, next){
var f = new fruits({}, req);
f.getAll(function(fruitsObj){
console.log(fruitsObj);
res.render('fruits',{
"title":"Fruits!",
"fruits":fruitsObj
});
});
});
module.exports = router;
What happens is whenever the fruits route is navigated to, I can't query the database. It says that the "connection" from "this.req.getConnection" is "undefined".
Is there any reason why I can't retrieve the database connection and query it based on the contents of these two files? I'm positive I have all my packages installed. I even ran npm install for all them again to make sure.
Thanks for your help in advance.
I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
I'm trying to incorporate a live user count on my website http://clickthebutton.herokuapp.com which uses Express JS. When trying to install socket.io I get this error:
GET /socket.io/socket.io.js 404 1.911 ms - 1091
Yes, I have used 'npm install socket.io --save'
I have looked around for answers, tried them and nothing has helped. If anyone thinks they know what's happening, a response would be well appreciated! Here's my code:
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 io = require('socket.io')(app);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// view engine setup
app.set('views', path.join(__dirname, '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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.ejs
<!-- socket.io -->
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
</div>
</center>
</body>
routes/index.js
var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
console.log(Object.keys(io.sockets.connected));
});
io.on('connection', function (socket) {
console.log('Socket.io connected!')
});
I only copy/pasted the code that referenced socket.io
Thanks!
In app.js alone you're creating three instances of socket.io, and once again in routes/index.js. There should be only one throughout your entire app.
A common setup for Express looks like this:
var app = require('express')();
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
});
var io = require('socket.io')(server);
If you need to reference either app, server or io in other files, you need to pass it as a variable.
EDIT: because you're using an express-generator based setup, the HTTP server will be created in bin/www and not app.js. In that case, you also need to create the socket.io server there:
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io')(server); // add this line
Again, if you need to reference io somewhere else in your codebase, you need to pass it along from there.
lately i started to play around with express.js the nodejs web framework. i'm making a simple form that send data to a express route.
I have a users.js route file and inside that there is a register route.
my user.js route file
router.post('/register', function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var passwordConfirm = req.body.passwordConfirm;
console.log(name);
my jade file which form is in it
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
label Name
input.form-control(name='name',type='text',placeholder='Enter Name')
and go on ...
console.log retunrs undefiend.
my app.js . I used express generator to generate project, as you can see i have multer and bodyparser
var bodyParser = require('body-parser');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// multer config inja
var upload = multer({ dest: './uploads' });
// 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 }));
// // handle express session
app.use(session({
secret: 'secret', //encryption key
saveUninitialized:true,
resave:true
}));
// // Passport
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// flash messaging via connect-flash
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You have to configure an express middleware to parse the body of your HTTP request before hitting your /register route.
multipart/form-data enctype
This kind of type is often use for file upload. A library like Multer can be helpful for this use case.
I don't see a file to upload in your example. So you should consider using a simple enctype like application/x-www-form-urlencoded enctype (default) (see below).
If you still want to use form-data enctype without file upload, you can use a library like express-busboy (built on top of busboy).
var app = express();
var bb = require('express-busboy');
bb.extend(app);
// ...
router.post('/register', function(req, res, next) {
// req.body contains your fields.
// ...
application/x-www-form-urlencoded enctype (default)
If you configure your form to use the application/x-www-form-urlencoded enctype, it's a little bit easier to handle in your route.
body-parser can be use as a middleware too: https://github.com/expressjs/body-parser#bodyparserurlencodedoptions
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
// ...
router.post('/register', function(req, res, next) {
// ...
```
I'm following the docs on the github of Share.js but can't seem to get it to work
https://github.com/share/ShareJS/wiki/Getting-started-%280.6.x%29
I built a base app with the Express generator. It put the main server file inside /bin/www which is not supposed to be modified (I tried it).
The problem is with the code below.
var connect = require('connect'),
sharejs = require('share').server;
var server = connect(
connect.logger(),
connect.static(__dirname + '/public')
);
var options = {db: {type: 'none'}}; // See docs for options. {type: 'redis'} to enable persistance.
// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(server, options);
server.listen(8000, function(){
console.log('Server running at http://127.0.0.1:8000/');
});
It requires me to set up server.listen(...) in the app.js but it's already been done in the /bin/www file.
My app.js looks like the code below.
var express = require('express');
var engine = require('ejs-locals');
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();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// database setup
var dbConfig = require('./db.js');
var mongoose = require('mongoose');
// connect to DB
mongoose.connect(dbConfig.url, function (err) {
if (err) {
console.log(err);
}
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'mySecretKey',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize passport
var initPassport = require('./passport/init');
initPassport(passport);
// Configuring Routes
var routes = require('./routes/index')(passport);
var users = require('./routes/users');
var editor = require('./routes/editor')(passport);
app.use('/', routes);
app.use('/editor', editor);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
if (req.session.user) {
app.locals.user = req.session.user
}
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;