Express get/post method error - javascript

I'm trying to learn node.js and I'm using express to have a form that should appear here: http://localhost:4000.
I started using "hello world" which worked well. Now with this second step I have a problem. If I select post method, it appears that I cannot GET on my browser. Also, if I select post method, the following appears:
Username: undefined.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="test.js"></script>
<title></title>
</head>
<body>
<form method="get" action="/">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Javascript
( post method is with comment)
var express = require('express');
var app = express();
/*
app.post('/', function(req, res) {
res.send('Username: ' + req.body.username);
});
*/
app.get('/', function(req, res) {
res.send('Username: ' + req.query['username']);
});
var server = app.listen(4000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
I know that most probably the error is due to something simple; I'm trying to solve alone but until now I have found no solution.

Related

Splitting HTML file doesn't work

I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):
Welcome.html & Welcome.css:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Welcome.css">
</head>
<body id="bodyTag">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
});
</script>
<div id="top" w3-include-html="/Top.html">
</div>
<div id="bottom">
bottom
</div>
</body>
</html>
#bottom {
height: 50%;
background-color: blue;
}
#top {
height: 50%;
background-color: orange;
}
I want that Welcome.html file will get the top content from external html file
Top.html
<html>
<head>
</head>
<body>
Test -> TOP
</body>
</html>
But is seems that there is no request for Top.html file in the Node.js Log:
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json())
/*
* Home page
*/
app.get('/', function (req, res) {
clearLogScreen();
console.log("[/] Got request for '/'");
res.sendFile( __dirname + '/Welcome.html');
})
app.get('/Welcome.css', function(req, res) {
console.log("[/Welcome] Got request for 'Welcome.css'");
res.sendFile(__dirname + "/" + "Welcome.css");
});
app.get('/Top', function(req, res) {
console.log("[/Top] Got request for 'Welcome.top'");
res.sendFile(__dirname + "/" + "Top.html");
});
/*
* Startup
*/
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
// start
console.log("-----------------------------")
console.log("Dirname: " + __dirname);
console.log("App listening at http://%s:%s", host, port)
})
I guess I'm missing something very easy, but can't find the mistake.
Kindly checkout templatesjs; It will help insert html inside another html.
I'm not sure what "w3-include-html" is, but if it does what it is supposed to do (based on the name), then try changing its value from "/Top.html" to "/Top". Or, alternatively, try changing the url route "/Top" to "/Top.html" in your express app.
One side note: Your included html ("Top.html") should not be a complete html. Try removing html, header and body tags. It should be a fragment.

get() method or function

Unresolved function or method get().
I'm new in js and node and I got stuck with this while trying to make a chat using sockets. Here is the code:
.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>glupi chat</title>
<style>
#chat{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message">
<input type="submit">
</form>
<script src='jquery-3.2.1.js'></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$document.ready(function () {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
I'm using IntelliJ IDEA, I have every module and library that I need installed.
It appears that you have no route for the jQuery file you specify with this:
<script src='jquery-3.2.1.js'></script>
A nodejs express server does not server ANY files by default so unless you have a general purpose route for your static files or a specific file for that jQuery file, your express server will not know how to serve that file when the browser requests it.
You have several possible choices for how to fix that:
Change the jQuery URL in the script tag in your web page to point to one of the public CDNs for jQuery. There are often performance advantages to doing this. For example, you could change to this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>.
Use express.static() on your server to configure a directory of static assets that will be automatically served by express when requested by the browser.
Create a specific route for the jQuery file just like you did with your exist app.get('/', ...)that responds to the/` GET request.

CSS file is not working in NODE js

For some reason, I have attached my css file to my html file. And then i open the html file using express in node js. However, the css file does not open when i run the webserver through node js. I thought since the css file is included in html that it should run??
html
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<h1>Reading in Value</h1>
<form action="/" method="post" >
<br/>
<label>Enter a UDP command in hex</label>
<br/><br/>
<input type="number" name="number" id="number">
<br/><br/>
<input type="submit" value="Submit" name="submit">
<meta name="viewport" content="width=device-width, initial-scale=1">
</form>
</body>
</html>
node js
//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express')
var fs= require('fs')
var util = require('util')
var dgram= require('dgram')
var client= dgram.createSocket('udp4')
var bodyParser = require('body-parser')
var app = express()
var app2= express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Reading in the html gile
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Sends user command utp
app.post('/', function(req, res){
//Define the host and port values
var HOST= '192.168.0.172';
var PORT= 69;
//buffer with hex commands
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) {
throw err;
}
res.send('UDP message sent to ' + HOST +':'+ PORT);
});
});
//CREATES ANOTHER PORT
app2.get('/', function(req, res){
client.on('message', function (message) {
res.send('received a message: ' + message);
});
});
app.listen(3000, "192.168.0.136");
app2.listen(8000, "192.168.0.136");
console.log('Listening at 192.168.0.172:3000 and Recieve message will be on 192.168.0.172:8000')
<link rel="stylesheet" type="text/css" href="style.css" media="screen" /> tells the browser to ask (with GET) the server for the CSS at /style.css.
Look at your server code. You've told it what to do with GET / (app.get('/', function(req, res){ etc), and you've told it what to do for POST /, but you haven't told it what to do for GET /style.css.
The Express manual covers this.
Wherever you're serving your files from, you need to set in the express config like this:
app.use(express.static('public'));
This would work if you're static files were being stored in a folder called public. Please see this link for more documentation: http://expressjs.com/en/starter/static-files.html

NodeJS writing response

First of all: I am a beginner at nodeJS!
My Problem is that i have an html-file, which is complex, and i want to write an individual response in it. For example
index.js
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('Listening at port 3000');
});
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + 'index.html');
//
// what to write here when i want to modify the index.html before sending?
//
});
index.html
<!DOCTYPE HTML>
<html>
<div id="writehere">
<!--I would like to modify the page here-->
</div>
</html>
I hope you can help me and understood my question!

Express' render/redirect does not work if the call isn't coming from a submit method in a form

Task
Perform a POST request from a JS method, so that variable values can be sent as parameters.
Environment
NodeJS
Express
BodyParser
ejs
My first attempt
Frontend:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
<script type="text/javascript">
function postAnswer() {
$.post('vote', { message: "hello!"}, function(returnedData) {
console.log("Post returned data: " + returnedData);
});
}
</script>
</head>
<body>
<button id='send' onClick='postAnswer()' class='btn btn-success btn-xs'>Svara</button>
</body>
</html>
Server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
require('./app/routes.js')(app);
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));
var server = require('http').createServer(app);
server.listen(8080);
console.log('Server running on port 8080...');
routes.js:
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('vote.ejs', {
message: ''
});
});
app.post('/vote', function(req, res) {
var msg = req.body.message;
console.log("Got POST request with message: " + msg);
res.render('index.ejs', {
message: ''
});
});
};
Result:
The render method won't render a new page. It will however return the entire 'index.ejs' file in the returnedData parameter.
Server:
Client:
Second attempt:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
<script type="text/javascript">
function postAnswer() {
$.post('vote', { message: "hello!"}, function(returnedData) {
console.log("Post returned data: " + returnedData);
});
return false;
}
</script>
</head>
<body>
<form action='/vote' method='post'>
<button id='send' type='submit' onsubmit='return postAnswer()' class='btn btn-success btn-xs'>Svara</button>
</form>
</body>
</html>
Result:
This does work, but it's not a very clean solution.
My questions:
Why doesn't the first attempt work?
How can I send variables as parameters to a POST request with a nice clean solution?
I'm not a jQuery expert, but I think the first attempt doesn't work because $.post makes an AJAX request, the same way as you would in a single-page app to interact with an API in the background.
Your second example submits a form, which is an in-browser action that performs a navigation action (as specified by the method attribute of the form). In this case, the event listener you add in jQuery is redundant, and should be removed - it's making another background POST request, before the form submits the content of its fields in its request.
As for your second question, the way to submit additional variables with a form submission (presuming that you actually want to do a navigating form submission and not an XHR background request against an API) is to use <input type="hidden"> elements.
So, to summarize, to do what you're describing in your question, your example HTML should look like this (minus the comments):
<!DOCTYPE html> <!-- only you can prevent quirks mode -->
<html>
<head>
<meta charset="UTF-8"> <!-- ༼ つ ◕_◕ ༽つ Give UNICODE -->
</head>
<body>
<form action='/vote' method='post'>
<input type="hidden" name="message" value="hello!">
<button id='send' type='submit' class='btn btn-success btn-xs'>Svara</button>
</form>
</body>
</html>

Categories

Resources