index.html arrives on the browser by clicking a link called 'spons' from the home page "localhost:9000/" and the url changes to "localhost:9000/spons" , now when i submlit the form , it goes to the url "localhost:9000/spons/uploads" and gives "cannot POST /spons/uploads" , the images folder is in the same directory as the server.js file , can you please help me with this and suggest a solution ?
this is the index.html file
<form name='uploadform' enctype='multipart/form-data' method='post' action='/spons/uploads'>
<input name='imageupload' type='file'>
<input type="submit" value="Upload Image" name="submit">
</form>
this is the server.js file
var express = require('express');
var multer= require('multer');
var upload= multer({dest:'/images'}).single('imageupload');
var router = express.Router();
router.post('/spons/uploads', upload, function(req,res){
res.end('uploaded');
}
);
express().listen(9000);
You were getting cannot POST /spons/uploads, because you did not attach router to the app.
var express = require('express');
var app = express();
var multer= require('multer');
var upload= multer({dest:'/images'}).single('imageupload');
var router = express.Router();
router.post('/spons/uploads', upload, function(req,res){
res.end('uploaded');
});
app.use('/',router); // this line is the key.
app.listen(9000);
Hopes, it helps.
You don't even need explicit router, check the sample below
var express = require('express');
var app = express();
var multer= require('multer');
var upload= multer({dest:'/images'}).single('imageupload');
app.post('/spons/uploads', upload, function(req,res){
res.end('uploaded');
});
app.listen(9000);
Related
I have a simple NodeJs app, and trying to build a simple authentification form. But for some reason, i'm not able to get the entred data in the form. Here's my code :
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser= require ('body-parser');
var user = require('./routes/user');
var login = require('./routes/login');
var jwt = require('jsonwebtoken');
var app = express();
app.use(bodyParser.json());
app.use(cookieParser());
app.get('/userprofile', user.getUserInfos);
app.post('/users', user.createUser);
app.get('/login', function (req, res) {
var html='';
html +="<body>";
html += "<form action='/login' method='post' name='logingorm' enctype=\"application/json\">";
html += "Username:<input type= 'text' name='username'><br>";
html += "Password:<input type='password' name='password'><br>";
html += "<input type='submit' value='submit'>";
html += "</form>";
html += "</body>";
res.send(html);
});
app.post('/login', user.login);
app.listen(3000);
console.log('Listening on port 3000...');
And then, the login function called when a post is received on /login :
exports.login= function(req, res) {
console.log(req.body);
}
Always get {} as result of my console.log
Any idea ?
Thanks a lot
application/json is not a valid form encoding. When the browser sees that, it falls back to application/x-www-form-urlencoded.
bodyParser.json() ignores requests with MIME types other than application/json, and even if it didn't, it wouldn't be able to parse the urlencoded data. Use bodyParser.urlencoded() instead.
app.use(bodyParser.urlencoded({extended: false}));
I think that might be because there is no 'value' attribute written for both the input tags. Try writing them and check.
I'm writing a simple server with expressjs:
'use strict';
var express = require('express');
var logger = require('morgan');
var path = require('path');
var bodyParser = require('body-parser');
var api = require('./routes/main');
var app = express();
app.disable('x-powered-by');
app.use(logger('dev')); //Used to log HTTP requests
app.use(bodyParser.urlencoded({ extended: true })); //Used to automatically parse requests body
app.use(bodyParser.json());
app.use('/api', api);
app.use('/*', express.static('./public')); //serving static files under public folder
app.use(function(req,res){
res.send("404");
});
var server = app.listen(8000, "0.0.0.0", function () {
console.log('RAVE listening on port ' + server.address().port + 'hosting at ' + server.address().address);
});
module.exports = app;
in public directory there are index.htm, some css files and one js script, When index.html tries to load css or js scripts, it does through GET /path/file.css/ and loads a directory instead of file.css. Why??
index.html:
<head>
....
<link rel="stylesheet" href="/stylesheets/view-style.css" type="text/css" />
<script type="text/javascript" src="/js/main.js"></script>
</head>
console:
GET /stylesheets/view-style.css/ 200 8.979 ms - 10602
GET /js/main.js/ 200 8.598 ms - 10602
chrome sources:
I know you have already solved the problem . But just for future reference .
We have something called cache-busting . Basically use
<script type="text/javascript" src="/js/main.js?version=1"></script>
Whenever you change the file change the version number in the code above
I am new to node js.
I am writing a nodejs application to fetch data from mongoDB and display on the page in a table. But the data is not getting displayed.
Usecase is:
User will navigate to localhost:8999/ to go to the main page called Queue. Here a link for a page HealthReport is present, clicking on which user would navigate to healthreport.html where I need to display the data from mongo.
I am able to view the json data in the browser, but displaying it in the required page is not working.
Is there any particular directory structure I need to follow ?
I am using a js file to do that but its not working.
That file is healthreport-db.js below:
$(function() {
var startTime = new Date();
startTime.setMonth(startTime.getHours() - 6);
$.ajax({
url : "http://localhost:8999/healthreport/getHealthReport",
dataType: "json",
success : function(data) {
var latest = data.length - 1;
var snapShotTime = moment.utc(data[latest].snapShotTime).toDate();
var nfs = data[latest].nfs;
var hive = data[latest].hive;
console.log("db.js hit");
// Add values to Hive Stats Table
$("#nfs").text("NFS: "+nfs);
$("#hive").text("HIVE: "+hive);
},
error : function() {
console.log("failed to get hiveInfo data");
}
});
});
healthreport.html file (where i need to display the parsed json data) in "views" directory:
<html>
<head>
<title>HealthReport</title></head>
<body>
Health Report
<table>
<tr>
<th>value</th>
</tr>
<tr>
<td id="nfs"></td>
</tr>
<tr>
<td id="hive"></td>
</tr>
</table>
<script src="healthreport-db.js"></script>
</body>
</html>
queue.html file in "views" directory:
<html>
<head>
<title>Queue</title></head>
<body>
Queue<br>
Health Report
</body>
</html>
I have a main js file called main_web.js:
var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');
var collectorConn = mongoose.createConnection('mongodb://localhost:27017/mongotest3');
exports.collectorConn = collectorConn;
var app = express();
var publicOpts = { maxAge: 86400000 }; // Max age of 1 day for static content
// Routes
var route = require('./route.js');
var healthReport = require('./healthReportRoute.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public', publicOpts)); //all client source will be in public folder
app.use(express.static('views')); //views folder contains html & ejs files
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile); //render html files as ejs
// Route handlers
app.use('/', route);
app.use('/healthreport', healthReport);
var port = process.env.PORT || 8999;
app.listen(port);
console.log("open your browser to localhost:" + port);
exports.app = app;
Then I have a route.js that is acting as the router:
var express =require('express');
var router = express.Router();
/* Home page */
router.get('/', function(req, res, next) {
res.render('./queue.html',{title: "Queue"});
});
router.get('/healthreport', function(req, res, next) {
res.render('./healthreport.html',{title: "HealthReport"});
});
module.exports = router;
And then I have a healthReportRoute.js that is able to fetch the json data on the web using the url localhost:8999/healthreport/getHealthReport :
var express =require('express'); //add express
var router = express.Router();
var moment = require('moment'); //add moment
//mongoose schema
var appTableProdSchema = require("./appTableProdSchema.js");
router.get('/getHealthReport', function(req, res) {
// Return the most recent document
var records = appTableProdSchema
.find()
.sort({'_id': -1})
.limit(1)
.exec(function(err, data) {
if (err) return res.sendStatus(500);
res.json(data);
});
});
module.exports = router;
The appTableProdSchema.js is :
var conn = require('./main_web').collectorConn;
module.exports = conn.model('AppTableProd', {
snapShotTime : String,
nfs: Array,
hive: Array
});
I dont know how to get the data into the healthreport.html page.
Please help
You are making heavy use of the jQuery library but have not imported it.
Every time you have $ in your healthreport-db.js, you are attempting to reference the jQuery library.
You can download the library and include it in your project or you can link directly to the library hosted at one of many cdn's. Here's the documentation and the code to import from google's cdn:
http://jquery.com/download/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Your healthreporter.html would look like this:
<html>
<head>
<title>HealthReport</title></head>
<body>
Health Report
<table>
<tr>
<th>value</th>
</tr>
<tr>
<td id="nfs"></td>
</tr>
<tr>
<td id="hive"></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="healthreport-db.js"></script>
</body>
</html>
I want to upload file using node.js , being new to it a tried to check if the file is being send to server.
html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="img" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
js
var express = require("express");
var app=express();
var http=require("http").Server(app);
app.get("/",function(req,res){
res.end("hello")
});
app.get("/upload",function(req,res){
res.sendFile(__dirname + "/form.html")
})
app.post("/img",function(req,res){
if(req.files){
console.log(req.files.file.name);
}
else{
console.log("ee")
}
});
http.listen(3000,function(){
console.log("listening on 3000")
})
When i upload something , it throws error
Cannot read files of undefined
Being new to back end i have no idea why its happening , why doesnt the server recieve the file?
You need to app.use() a fileparser. For example, you could use connect-busboy. You can get more information about options and usage at above link; a simple setup would be somehting like this:
var busboy = require('connect-busboy');
app.use(busboy());
app.post("/img",function(req,res){
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
// ...
});
req.busboy.on('field', function (key, value, keyTruncated, valueTruncated) {
// ...
});
req.pipe(req.busboy);
// etc ...
});
As stated in the above answer, you must use a body parser for multipart bodies, but the better solution is to use the express middleware multer which lets you to use req.files just like in your OP.
Also, multer is built on top of busboy which is the fastest multipart body parser for node.js
With multer:
var express = require('express'),
multer = require("multer"),
app = express();
app.use(multer({
dest: path.resolve(__root + path.sep + config.get("localFolders").rawImages),
limits: {
files: 2
}
}));
// handle file upload
app.post("/img", function (req, res, next) {
var image = req.files.image;
// do something with image;
console.log(image.name);
});
Have a look on the documentation for multer within the link provided above. Good luck. :)
I'm trying to get form data to node server using POST method.
This is my HTML code,
<html>
<head>
<title>
Node Architecture
</title>
</head>
<body>
<h1>Node Architecture</h1>
<h3>Enter Your name.</h3>
<form action="/" method="POST">
<input type="text" name="eventname" />
<input type="submit" value="Go" />
</form>
</body>
</html>
This is my node app, index.js
var app = require('express')();
var http = require('http').Server(app);
//var io = require('socket.io')(http);
//var qs = require('querystring');
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.get('/events', function(req, res){
res.sendfile('events.html');
});
app.get('/movie', function(req, res){
res.sendfile('movie.html');
});
app.post('/', function(req, res) {
var name = req.body.eventname;
console.log(name);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now when I click submit I get an error message which is as follows,
TypeError: Cannot read property 'eventname' of undefined at Object.handle
How do I print the entered name to my console?
Express doesn't parse request body by default, you will have to use a middleware to do that.
Try this.
var express = require('express');
var app = express()
.use(express.bodyParser());
...
...
Also, you should read this article. It explains some of the problems (and their solutions) related to common body parsing approach.
Add these lines into your app.js.
require body-parser.
var bodyParser = require('body-parser');
put before your first app.get that will be better.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
good luck.