Node.js Express receiving postman as empty - javascript

I'm working on a simple website and I'm having a problem when sending a JSON to the API. The JSON will be received as EMPTY if is sent using the html/js, but when using postman everything works as expected.
The structure of files is simply the server running on node.js, an html page with his javascript to build the JSON and send it.
The html file code as it follows :
<!DOCTYPE html>
<html lang="en">
<head>
<body>
</head>
Receiver Address
<input type="text" placeholder="Write the target address..." id="target_address"></input><br>
Message
<input type="text" placeholder="Write the message in plain text..." id="message"></input><br>
<input type="submit" value="Send" id="accept"></input>
<br>
<div id="results"><div>
</body>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
</html>
The javascript file is :
var URL_API = "http://localhost:3000/nr";
$("#accept").click(function(e) {
e.preventDefault();
var url = URL_API;
var object = new Object();
object.L = 1;
object.B = ($("#target_address").val());
object.message =($("#message").val());
object.po = "ProofofOrigin";
var data = JSON.stringify(object);
console.log(data);
$.ajax({
url : url,
type : 'POST',
crossDomain : true,
dataType : 'json',
contentType : 'application',
data : data,
dataType:'json',
}).done(function(data, status, jqxhr) {
window.alert("Information sent successfully");
console.log(data.B);
}).fail(function(data) {
window.alert("ERROR");
});
});
Then the part of node which is executing when receiving the given POST :
router.post('/', function(req, res, next) {
var updateStep = Number(req.body.L)+1;
var ProofofOrigin = req.body.message + "Message signed - POO";
var info_JSON = {
address: req.body.B,
step: updateStep,
message: req.body.message,
po: req.body.po,
};
JSON.stringify(info_JSON);
//res.send("Address : " + req.body.B + " \nStep : " + req.body.L + " \nMessage : " + req.body.C + " \nPOO : " + req.body.Po);
res.send(info_JSON);
//console.log(info_JSON);
});
For some reason the req.body (where the JSON should be saved) is completely empty on the body, but if I send it using Postman it will work.
I don't know what could be wrong.

Please verify this:
In javascript (client side):
contentType : 'application/json',
In nodejs (server side):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/api/doSomething', function(req, res) {
var mydata = req.body.mydata;
...
return res.json({result: result});
});
You need to include the body parser module to be able to parse JSON bodies.

Related

Client side js file is not working | node.js

So I just made a HTML page added a script tag with src to a js file and sent the HTML file as response with node js using HTTP module.
But the js file is not working and when I checked the network tab I saw js file is received as text/html file.
Following are the js and html codes.
Server code with node js
const http = require('http') ;
const file = require('fs') ;
const server = http.createServer((req, res) => {
file.readFile('public/login.html', (err, data) => {
if (err) throw err ;
res.writeHead(200, {'Content-Type': 'text/html'}) ;
res.write(data) ;
res.end() ;
})
}) ;
server.listen(5000) ;
front end code : login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script defer src="js/index.js"></script>
</head>
<body>
<h1>Login</h1>
<form action="" method="post">
<input type="email" name="user" id="user">
<input type="password" name="pass" id="pass">
<button type="submit" name="button" value="login">Login</button>
</form>
</body>
</html>
now when I load the page at localhost:5000, js does not execute and it's received as text/html.
The browser will receive the HTML, see the script tag, and request js/index.js from your server. But your server only sends your HTML file. It doesn't pay any attention to what the browser requested, it just always sends back the HTML. So the script is never sent to the browser, so the browser can't execute it.
Your server code needs to look at req to determine what was requested (looking at url, etc.), and send an appropriate response, rather than always sending back the same content.
Here's a fairly simple example that handles /, /login.html, and /js/index.js paths (making the first two synonyms):
const http = require('http');
const file = require('fs');
const FILENAME_404 = "public/404.html";
const server = http.createServer((req, res) => {
let filename = null;
let contentType = "text/html";
let status = 200;
// What did the browser ask for?
switch (req.url.toLowerCase()) {
case "/":
case "/login.html":
// The login page
filename = "public/login.html";
break;
case "/js/index.js":
// The JavaScript file
filename = "public/js/index.js";
contentType = "text/javascript";
break;
default:
// Something we don't support -- send a 404
filename = FILENAME_404;
status = 404;
break;
}
sendFile(res, filename, contentType, status);
});
function sendFile(res, filename, contentType, status, callback) {
file.readFile(filename, (err, data) => {
if (err) {
// Couldn't read the file, send a 404
if (filename !== FILENAME_404) {
sendFile(res, FILENAME_404, "text/html", 404);
} else {
// Couldn't even find the 404 file, send a minimal plaintext 404
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("The requested resource does not exist on this server.");
res.end();
}
} else {
res.writeHead(status, {"Content-Type": contentType});
res.write(data);
res.end();
}
});
}
server.listen(5000);
Note: This is just an example. If you're going to build anything of any size, you'll want more structure than this. You might look at Express or Koa or others that handle more of the HTTP plumbing, URL routing, etc. for you and have modules available for other things as well.

How to send variables from Node.js to Socket.io and display on local webpage?

I'm working on a project where my job is to use Node.js and Socket.io to read a text file (contain 3 real time readings) and got the data in 3 variables, then send them to Socket.io and get them displayed on the website continuously without having to refresh it. I ran my codes, it did not give any errors, but it did not display anything on the website either. So I don't know what is wrong in my code. I need help with passing variables from Node.js to Socket.io and get them displayed on the my web page.
This is my server file:
var http = require('http').createServer(handler); //require http server, and cr$
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the htt$
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/index.html', function(err, data) { //read file inde$
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {
setInterval(function(){
var array = fs.readFileSync('report.txt').toString().split("\n");
var volt = (array[0]);
var power = (array[1]);
var temp = (array[2]);
socket.emit('volt',{'volt': volt});
socket.emit('power',{'power': power});
socket.emit('temp',{'temp': temp});
}, 1000);
});
index.html file :
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://10.117.230.219:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
socket.on('power', function (data) {
$('#power').text(data.power);
socket.on('temp', function (data) {
$('#temp').text(data.temp);
});
</script>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
You are missing some tags on your HTML page including HTML and head. You are also missing a closing )} for each socket.on(...) call in your script. This is what it should look like:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
})
socket.on('power', function (data) {
$('#power').text(data.power);
})
socket.on('temp', function (data) {
$('#temp').text(data.temp);
})
</script>
</head>
<body>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
</html>
This should do it.

jQuery Ajax Post - 404 error - Local server

I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.

Issues in image upload using Express JS and Parse Cloud hosting

I am using Cloud Code and Express, hosted on Parse to upload an image.
Here is the error on Parse log:
I2015-01-03T13:35:55.199Z] TypeError: Cannot read property 'thumbnail' of undefined
at app.js:40:25
at callbacks (express_router.js:161:37)
at param (express_router.js:135:11)
at pass (express_router.js:142:5)
at Router._dispatch (express_router.js:170:5)
at Object.router (express_router.js:33:10)
at next (connect_proto.js:240:15)
at Object.expressInit [as handle] (express_middleware.js:31:5)
at next (connect_proto.js:240:15)
at Object.query [as handle] (connect_query.js:44:5)
It seems that Express JS/Parse is not able to understand req.files.XXX. There error is coming in app.js at following line: console.error(req.files.thumbnail.size);
Also, req.files print following error: No Message provided
Here is the recipecontent.ejs code:
<!DOCTYPE html>
<html>
<form method="post" enctype="multipart/form-data" action="/saverecipecontent">
Enter Recipe Image 1:
<input type="file" name="thumbnail" id="thumbnail">
<input type="submit">
</form>
</html>
Here is app.js code:
// These two lines are required to initialize Express in Cloud Code.
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
app.get('/recipecontent', function(req, res) {
res.render('recipecontent', {
recipe_name: 'e.g. Rice Cake'
});
});
app.post('/saverecipecontent', function(req, res) {
console.error(req.files.thumbnail.size);
console.error(req.files.thumbnail.path);
console.error(req.files.thumbnail.name);
console.error(req.files.thumbnail.type);
Parse.Cloud.run('saveRecipeImage', req.body, {
success: function(result) {
// result is 'Hello world!'
},
error: function(error) {
}
});
});
// Attach the Express app to Cloud Code.
app.listen();
Finally here is the main.js code:
require('cloud/app.js');
Parse.Cloud.define("saveRecipeImage", function(request, response) {
var recipeContent = Parse.Object.extend("recipe_content");
var recipeContentObj = new recipeContent();
console.error(request.params);
var file = request.params.thumbnail;
var name = "photo.jpg";
var parseFile = new Parse.File(name, file);
parseFile.save().then(function(parseFile) {
// The file has been saved to Parse.
var url = parseFile.url();
recipeContentObj.set("recipe_imgurl1", url);
return recipeContentObj.save();
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
});
Please help!
I raised this bug in Parse, here is the update:
The middleware we support for express.js does not support file uploads.
What you can do instead is sending the file contents as base64 to your endpoint and create the Parse.File object from this data.
Here is the updated code utilizing file contents as base64 to endpoint and creating Parse.File object:
Here is the layout.ejs code
< html >
< head >
< script src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > < /script>
<script src="/ / cdnjs.cloudflare.com / ajax / libs / underscore.js / 1.4.4 / underscore - min.js "></script>
<!-- <% if (locals.title) { %> -->
<!-- <title><%= title %></title>
<% } else { %>
<title>AnyImg</title>
<% } %> -->
<link href='//fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src=" / javascripts / backbone.js "></script>
<script src="
https: //www.parsecdn.com/js/parse-1.2.8.min.js"></script>
< script >
Parse.initialize("n47hKoBkN2vbAAjIPd8rj6Dnc9P6zKYIlXvlZo3x", "a960Z8aOzTNOaKMUcvDQ7lvzT2v2VTHABh6lAdNx"); < /script>
<script type="text/javascript
" src=" / javascripts / main.js "></script>
</head>
<body>
<div id="
content ">
<div id="
bar ">
<h1>File Upload</h1>
</div>
<div id="
main ">
<form id="
upload ">
<div class="
outer ">
<div>
<input type="
text " name="
title " placeholder="
Untitled " />
<input id="
asd " type="
file " />
</div>
</div>
</form>
<img id="
img " src="
" />
<div id="
base "></div>
</div>
</div>
</body>
</html>
// These two lines are required to initialize Express in Cloud Code.
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.json());
app.use(express.urlencoded());
app.get('/', function(req, res) {
res.render('layout', {
recipe_name: 'e.g. Rice Cake'
});
});
app.post('/newUploadImage', function(req, res) {
var file = new Parse.File("logo.png", {
base64: req.body.image
});
file.save().then(function() {
console.log("file saved");
console.log(file.url());
});
if (req.params.image) {
console.log("data found12345");
}
});
app.listen();
Here is the image js
var base64Data;
var imageName = '';
function readImage(input) {
if (input.files && input.files[0]) {
imageName = input.files[0].name;
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
$('#base').text(e.target.result);
base64Data = e.target.result;
var datObj = {
image: e.target.result,
name: imageName
};
var test = {
image: '12sds'
};
$.ajax({
type: "POST",
data: datObj,
url: '/newUploadImage',
dataType: "json",
success: function(msg) {
alert(msg.url);
console.log();
},
error: function(errormsg) {
console.log(errormsg);
alert("Sorry, there was an error uploading the image.");
}
});
};
FR.readAsDataURL(input.files[0]);
}
}
$(function() {
// Make all of special links magically post the form
// when it has a particular data-action associated
$("#asd").change(function() {
readImage(this);
alert('Test');
});
});
Thanks!
It looks like you're trying to use body-parser middleware to parse a multipar body but as stated on the github page of body-parser itself:
This does not handle multipart bodies, due to their complex and
typically large nature.
You need another parser to handle multipart bodies.
I suggest you multer but there are many others available.

execute javascript file in dynamically created html page with nodejs webserver

i want to execute the javascript file in the header of an dynamically created html page with a node.js webserver. can't figure out how but must be possible.
var http = require('http');
var url = require('url');
function processRequest(request, response) {
"use strict";
var pathname = url.parse(request.url).pathname;
console.log('Requested ' + pathname);
response.writeHead(1000, { 'Content-Type': 'text/html' });
response.write('<!DOCTYPE html><html ><head>');
response.write('<meta charset="utf-8">');
response.write('<title>' + 'Yay Node!' + '</title>');
response.write('<link rel=stylesheet href=../styles/styles.css rel=stylesheet />');
response.write('<script src=script.js type=text/javascript></script>');
response.write('</head><body>');
response.write('<h1><tt>' + 'jan' + '</tt></h1>');
response.write('<script type="text/javascript">test()</script>')
//response.write('<script type="text/javascript">script.onload = function () { alert("from html Node!")}; </script>')
response.write('<input id="clickMe" type="button" value="clickme" onclick="test()" />')
response.write('</body></html>');
response.end();
};
http.createServer(processRequest).listen(8888);
script.js:
document.onload = function () { alert('load Node!'); };
test = function() { alert('test Node!') };
the problem is, that your browser can't find script.js
When it tries to get http://localhost:8888/script.js node answers with an html file that is the same as http://localhost:8888/.
In order for node to correctly serve the script file, you need to check the path and send the correct file.
add something like this to your processRequest function
if (pathname === '/script.js') {
//code to send script
} else {
//code to send html
}
you would have to do the same for the styles.css file as well
if you don't want to hardcode every file in your page, I would recommend using the npm module express
var express = require('express'),
app = express(),
server = require('http').createServer(app);
app.use('/', express.static(__dirname + '/static');
server.listen(8888);
this code will automatically send the files in /static when the browser requests them.
if you want to create a dynamic page, you can add this between the app.use and the server.listen
app.all('/somedynamicurl', function (request, response) {
//Dynamic page
});
now, if someone goes to http://localhost:8888/somedynamicurl they'll get this dynamic page.
I'd also recommend reading the express guide and the express docs
this works. thanks to Ferdi265.
// http://www.cburch.com/cs/340/reading/nodejs/
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var mimeTypes = {
'.js': 'text/javascript',
'.html': 'text/html',
'.css': 'text/css'
};
function processRequest(request, response) {
"use strict";
var pathname = url.parse(request.url).pathname;
console.log('Requested ' + pathname);
var lookup = path.basename(decodeURI(request.url)), //|| 'index.html',
f = lookup;
fs.exists(f, function (exists) {
if (exists) {
fs.readFile(f, function (err, data) {
if (err) {
response.writeHead(500);
response.end('Server Error!'); return;
}
var headers = {
'Content-type': mimeTypes[path.
extname(lookup)]
};
response.writeHead(200, headers);
response.end(data);
});
// return;
}
else {
response.writeHead(1000, { 'Content-Type': 'text/html' });
response.write('<!DOCTYPE html><html ><head>');
response.write('<meta charset="utf-8">');
response.write('<title>' + 'Yay Node!' + '</title>');
response.write('<link rel=stylesheet href=../styles/styles.css rel=stylesheet />');
response.write('<script src=script.js type=text/javascript></script>');
response.write('</head><body>');
response.write('<h1><tt>' + 'jan' + '</tt></h1>');
response.write('<script type="text/javascript">test()</script>')
//response.write('<script type="text/javascript">script.onload = function () {
alert("from html Node!")}; </script>')
response.write('<input id="clickMe" type="button" value="clickme"
onclick="test()" />')
response.write('</body></html>');
response.end();
}
});
};
http.createServer(processRequest).listen(8888);

Categories