I have the following code
<!--index.html-->
<form id = "lang" action="/myform" method="POST" >
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
and
//index.js
var fileServer = new(nodeStatic.Server)();
var app = http.createServer( function(req, res){
fileServer.serve(req, res);
}).listen(port);
var io = socketIO.listen(app);
io.sockets.on('connection', function(socket) {
console.log('recieved connection ');
// convenience function to log server messages on the client
How do I send data in the textbox with id "lang" over to index.js and store it in some variable?
using express by placing it as a parameter in http.createServer() and executing filsServer.serve(req, res) in a callback:
express = require('express');
app2 = express();
http = require('http');
app2.post('/myform', function(req, res){
console.log(req.body.mytext);
});
var app = http.createServer(app2, function(req, res){
fileServer.serve(req, res);
}).listen(8082);
this obviously wouldn't work because I need the index.html page to load to fill in the form to begin with and by executing the code above, the program is expecting some form data even before the html page can load.
Is there another way I can send the data?
I got it to work. Here's the code:
var express = require('express');
var app2 = express();
var bodyParser = require("body-parser");
var path = require('path');
var socketIO = require('socket.io');
app2.use(bodyParser.urlencoded({ extended: false }));
app2.use(bodyParser.json());
var app = http.createServer(app2);
`var io = socketIO.listen(app);`
app2.use( express.static(__dirname));
app2.post('/form', function(req, res){
var lang = req.body.mytext;
console.log( req.body.mytext);
res.send(lang);
});
app.listen(8081);
Despite having created a server using express, I still needed to create the server using the HTTP module because an express server doesn't work with the socket.io module.
And I had used the express server to take care of my static files.
Related
I have a simple node script in which I update the db.json file through the form. It updates the file but when I render it in response for a get or post out it gives previous results only.
var cors = require('cors')
const express = require('express');
const app = express();
var jsonfile = require('jsonfile');
var file = './db.json'
var filex = require('./db.json')
app.engine('html', require('ejs').renderFile);
app.use(cors())
const http = require('http');
const port = process.env.PORT || 3000
const bp = require('body-parser')
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))
app.set('view engine', 'html')
// Defining get request at '/' route
app.get('/', function(req, res) {
res.send("<html><head><title>Json</title></head><body><form id='form1' action='/gettingdata' method='post'><input type='text' name='usrid' /><button type='submit' form='form1' value='Submit'>Submit</button></form></body></html>")
});
app.post('/gettingdata',function(req,res){
var user_id = req.body.usrid;
var obj = JSON.parse(user_id)
jsonfile.writeFileSync(file, obj,{flag: 'w'});
res.send('updated');
})
app.post('/api',function(req,res){
res.send(filex)
})
app.get('/api',function(req,res){
res.send(filex)
})
//extra
app.post('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.get('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.listen(port, function(req, res) {
console.log("Server is running at port 3000");
});
It only gives updated results on redeveloping of server.
var filex = require('./db.json')
So, filex only load the file when the server starts. If you try to get the most updated content of file db.json, please re-load the file.
I guess res.send(require('./db.json')) may work as expected.
I have solved this issue using
delete require.cache[require.resolve('./db.json')]
I'm trying to call a socket.on() event from an external .js file and I can't figure out what I'm missing...
I'm using NodeJS with ExpressJS.Below are the files:
app.js(the server file)
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
var io = require('socket.io')(http);
....
//Socket Io functions
const ioObj = require( './library/io.js')(app, express, io);
// This route will be used to print the type of HTTP request the particular Route is referring to
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
....
/library/io.js (sockets file)
module.exports = function(app, express, io){
io.on('connection', async function(socket) {
socket.on('refreshPage', function(){
console.log("page should now be refreshed !!");
socket.emit("refreshPageNow");
});
....
});
}
What I'm trying to do is to call/access the refreshPage event from /library/io.js so I can send further a "refresh webpage" signal.
I tried to do something like :
io.sockets.emit("refreshPage");
and
ioObj.sockets.emit("refreshPage");
But didn't work...
I am fairly new to node.js.
I am currently using lowdb for my database while I get the app started.
In the index.js file I have:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var path = require('path');
var low = require('lowdb');
var db = low('db.json');
var routes = require('./routes');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, '/public')));
app.use('/', routes);
server.listen(3000, function(){
console.log('listening on port 3000');
});
Then in my routes file I have something like:
var express = require('express');
var router = express.Router();
var account = require('./controllers/accounts.js');
router.post('/login', account.login);
router.get('/', function(req, res){
res.render('home');
});
module.exports = router;
And finally in my account controller I have:
exports.login = function(req, res){
var email = req.body.email;
var password = req.body.password;
...
}
The routing to controller system works. However I need to access the lowdb object from all of my routed controller functions (and also possibly elsewhere).
If in app.js I set:
global.db = db;
Then it seems to work, but from what I have read, setting this globally isn't the ideal solution. What is the appropriate way to be able to access the db from the controller files without having to set the db connection in every single file.
In your index.js file (application root) store the lowdb object in your express object :
var app = express();
var db = low('db.json');
app.db = db;
In your controller (accounts.js), access your database with req.app.db :
exports.login = function(req, res){
var email = req.body.email;
var password = req.body.password;
var db = req.app.db;
}
It looks like you can probably just setup and use the db directly in your routes file since you're not actually using the db in your main file. If it's that simple then I'd opt for doing that:
// routes file
var low = require('lowdb');
var db = low('db.json');
Alternatively, if you need to setup your db in the main file and pass it into the routes file and/or other modules, instead of exporting the router directly in the routes file, export a function which takes the db as input and returns the router. Then you can pass the db into the routes module when you require it.
// routes file
module.exports = function (db) {
// router setup using the input `db`
// ...
return router;
}
// index.js
var low = require('lowdb');
var db = low('db.json');
var routes = require('./routes')(db);
actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.
here is the code :
var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
To send a single file for a specific route use the res.sendFile() function.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});
app.listen(3000);
In case you want to serve all files in a directory use the express.static() middleware
var express = require('express');
var app = express();
app.use(express.static('path/to/my/directory'));
app.listen(3000);
With express u can do something like
//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
app.use(express.static("./file"));
})
server.listen(8000);
Edit: i fixed it by using:
app.configure(function(){
app.use(express.bodyParser());
});
Original post:
I'm trying to figure out how to handle a post with node and express and i'm completely stuck.
After some reading i noticed people saying i should use 'middleware' whatever that means and create a line app.use(express.bodyParser());. I assumed that after adding that i would have a req.body available in my post method. This isn't the case however. It console.log's into a undefined.
I think I don't know how to properly set this up, so here goes nothing:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, UserProvider = require('./userprovider').UserProvider,
qs = require('querystring');
var userProvider = new UserProvider('localhost', 27017);
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/new_game', function (req, res) {
res.sendfile(__dirname + '/new_game.html');
});
app.post('/new_game', function(req, res) {
var codeToUse = Math.random()*10000;
codeToUse = Math.round(codeToUse);
console.log(req.body);
});
app.use(express.bodyParser());
app.listen(3000);
Though you've said now your code works, but i won't suggest you to use bodyParser in the options of
app.configure()
What it does is that, if you use it as you have done, any file can be send into your system for all post requests. It's better if you use
express.json()
and
express.urlencoded()
in the options of
app.configure(),
and when you expect a file use bodyParser in the respective post route like this
app.post('/upload', express.bodyParser(), function(req, res){//do something with req.files})