When I click "ajaxsend" button, the result shows "undefined" on the console.
how can I check that function res.json is working fine?
app.js
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.listen(3000, function() {
console.log("start!! express server on port 3000");
});
app.use(express.static('public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.post ('/ajax_send_email', function(req, res){
console.log(req.body.email)
var responseData = {'result':'ok','email':req.body.email}
console.log(responseData)
res.json(responseData)
});
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>email form</title>
</head>
<body>
<form action="/email_post" method="post">
email : <input type="text" name="email"><br/>
submit <input type="submit">
</form>
<button class="ajaxsend">ajaxsend</button>
<div class="result"></div>
<script>
document.querySelector('.ajaxsend').addEventListener('click',function(){
var inputdata = document.forms[0].elements[0].value;
sendAjax('http://127.0.0.1:3000/ajax_send_email',inputdata);
})
function sendAjax(url, data){
var data = {'email' : data};
data = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.send(data);
xhr.addEventListener('load', function() {
console.log(xhr.reponseText);
});
}
</script>
</body>
</html>
I expect console shows "{result:ok, email:content in input text "email"}
but the actual output is "undefined".
Related
I am using sockets to send a file. On the server side I am listening to stream from the client side, but from the client side, I am not able to send data in chunks which can be sent to the server side.
I used FileReader to read the file in slices can you please tell what is that I am doing wrong?
Client Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Echo server</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<h1>File Upload</h1>
<form id="form" id="chat_form">
<input type="file" id="file_input" />
<input type="button" onclick="submit1()" value="submit">
</form>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io('localhost:8080');
var fReader;
socket.on('echo', function (data) {
console.log(data);
});
socket.emit('echo', 'this is a message');
function submit1() {
var file = $("#file_input")[0].files[0];
var reader = new FileReader();
reader.onload = function (evnt) {
socket.emit('join', { 'Name': Name, Data: evnt.target.result });
}
reader.readAsArrayBuffer(file);
}
</script>
</body>
</head>
SERVER code
var http = require('http')
var fs = require('fs');
var express = require('express')
var socketio = require('socket.io')
var app = express(server)
var server = http.Server(app)
var io = socketio(server)
app.get('/', function(req, res){
res.sendFile(__dirname + '/client.html')
});
io.on('connection', function(socket){
var writeStream = fs.createWriteStream(__dirname +'/m.png');
socket.on('echo', function(data){
socket.emit('echo', data);
});
socket.on('join', function(chunk){
console.log(chunk, "==============chunk=====================");
writeStream.write(chunk);
})
});
You never give the file object to your FileReader object. In fact, you never do anything with it so the FileReader object never has anything to do. For example, you may want to do:
reader.readAsArrayBuffer(file);
It also doesn't look like you're getting the data from the reader object correctly. There's a code examples here: File upload with socket.io and Send Images through Websockets.
js application. Need help to resolve this issue.
I have app.js which is node, calls index.html. The index.html intern calls main.js function clicked. It works fine when I have funtion 'clicked()' embeded inside index.html using script tag. But does not work if function clicked is in a seperate js file. I think this is something regarding to node.js but unable to figure out. Please find my code below.
app.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
var request = require('request');
request('http://localhost:8000/test', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
server.listen(3000,'127.0.0.1');
console.log('Listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<script type="text/javascript" src="main.js"></script>
<center>
<h1> Login </h1>
</center>
</head>
<body>
<center>
<input type="text" id="username" placeholder="UserName"></br>
<input type="password" id="password" placeholder="PassWord"></br>
<input type="button" value="Login" onclick="clicked()">
</center>
</body>
</html>
main.js
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var checkuser = "test";
var checkpass = "123"
if (user.value == checkuser) {
if (pass.value == checkpass) {
window.alert("You are logged in as "+ "'"+user.value+"'");
open("http://www.yahoo.com");
}
else
window.alert("Incorrect username or Password");
}
else
window.alert("Incorrect username or Password");
}
ScreenShot of the Error:
This is because the Node.js server does not serve main.js correctly -- According to the browser's "Resources" panel, main.js is available, but its path is not /main.js.
Low level Node.js server code and Express framework code co-exist, which is not a good idea.
To solve the problem with low level Node.js code:
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
if (req.url === '/main.js') {
res.writeHead(200,{'content-Type': 'application/javascript'});
var jsReadStream = fs.createReadStream(__dirname + '/main.js','utf8');
jsReadStream.pipe(res);
return;
}
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
To solve the problem with Express framework:
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/main.js', function(req, res) {
res.sendFile(path.join(__dirname + '/main.js')); // where main.js located.
});
app.set('port', 3000);
var server = http.createServer(app);
server.listen(port);
You are using both http and express, which is probably unnecessary. I would serve static files with app.use(express.static('public')), per the docs. Then you can serve the index with
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
And start the server with app.listen(3000);
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
Whenever I go to http://localhost:8080/search (search.html), it loads all of the html, then it reaches the client-side javascript and crashes. The first console.log in searchClient.js works, but not the second. The error is that io is not defined.
server.js:
var http = require('http');
var express = require('express');
var anyDB = require('any-db');
var engines = require('consolidate');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var conn = anyDB.createConnection('sqlite3://riverdata.db');
app.engine('html', engines.hogan);
app.set('views', __dirname + '/templates');
app.use(express.static(__dirname + '/public'));
app.get("/", function(request, response){
response.render('home.html');
});
app.get("/search", function(request, response){
response.render('search.html');
});
io.on('connection', function(socket){
socket.on('join', function(){
});
socket.on('search', function(toShowList, conditionsList){
var data = conn.query('SELECT toShowList FROM riverdata WHERE conditionsList');
console.log("im in socket.on(search)");
socket.emit('data', data);
});
socket.on('disconnect', function(){
});
});
app.listen(8080);
searchClient.js:
console.log("begins");
var socket = io.connect();
console.log("keeps running");
window.addEventListener('load', function(){
console.log("page loads");
var search = document.getElementById("searchButton");
submit.addEventListener("click", search, false);
socket.emit('join');
socket.on('data', function(data){
console.log(data);
})
}, false);
function search(){
console.log("button clicked");
var toShowList = [];
var conditionsList = [];
socket.emit('search', toShowList, conditionsList);
}
search.html:
<!DOCTYPE HTML PUBLIC>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='localhost:8080/socket.io/socket.io.js'></script>
<script type="text/javascript" src="/searchClient.js"></script>
<title>Envirostats Database</title>
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<body class="search">
<form action="">
<input type="checkbox" name="data" value="data"> Show Date <br>
<input type="checkbox" name="data" value="river"> Show River <br>
</form>
<button id=searchButton> Search </button>
</body>
</html>
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.