simple express json parser - json

trying to copy a simple example but still cannot parse json post request,
ideas?
looking in the borwser (firefox) network tab, I see the request with json params.
but the server log comes out empty.
client
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
server
//require the express nodejs module
var express = require('express'),
//set an instance of exress
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
//support parsing of application/json type post data
app.use(bodyParser.json());
app.post('/', function(req, res){
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
res.send("done");
});
//Start listen on port
const port = 8080;
app.listen(port);
console.log("Node js listen on port " + port + "...");

You are not setting Content-Type header with your AJAX request. Please change to the following.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>

well....
I guess I forgot these as well (working now)
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, **POST**, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

Related

Read static files with express got "Cannot Get /"

I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...
terminal show success
website show error
And the following is my code:
C:\...\1-on-1-webrtc\server.js
const express = require('express')
const app = express()
const http = require('http').createServer(app)
// static data
app.use('/', express.static(__dirname + '/public/'))
// TODO: Signaling
//start server listen 8080 port
http.listen(8080, () => {
console.log(`Server running in 8080`)
})
C:\...\1-on-1-webrtc\pubilc\index.html
(origin)
"hello"
(after)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
I change Your code a little and here is my solution:
Firstly change your name of public folder to correct. Not "pubilc" only "public".
Folder & File Structure:
server.js :
const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);
// static data
app.use("/", express.static(__dirname + "/public"));
//start server listen 8080 port
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html (without any changes) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
Output :
Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10

sending parsed JSON file to client but format is not HTML

called the API, and parsed the JSON. Now want to display that parsed JSOn in table format in receiving page. it is coming as plain text.
API url is just for test purpose taken from WIKI, cannot post actual API for security purpose.
requiremtn is to send the HTMl file in table format as a output.
app.js file:
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
var fs = require('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
const url = "https://en.wikipedia.org/w/api.php?
format=json&action=parse&page=Anthony%20Martial";
https.get(url, function(response) {
https.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
const jsonDATA = JSON.parse(data).parse;
var jsonText = jsonDATA.text;
var jsonTitle = jsonDATA.title;
var jsonPageid = jsonDATA.pageid
var str = JSON.stringify(jsonText);
var str1 = str.replace(/\\n/g, '');
const jsdom = require("jsdom");
const {
JSDOM
} = jsdom;
const virtualConsole = new jsdom.VirtualConsole();
const dom = new JSDOM(str1, {
virtualConsole,
runScripts: "dangerously",
resources: "usable"
});
var strWrite = dom.window.document.querySelector("table").textContent;
res.setHeader("Content-Type", "text/html");
res.write(strWrite);
res.send();
});
});
});
});
app.listen(3000, function(req, res) {
console.log("server is running in port 3000");
});
index.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>weatehr App API</title>
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<form action="/" method="post">
<label for="cityInput">City Name:</label>
<input id="cityInput" type="text" name="cityName">
<button type="submit"> Go </button>
<h3>hello</h3>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
output i am receiving:
in plaintext format:
Anthony MartialMartial playing for Manchester United in 2017Personal informationFull nameAnthony
Jordan Martial[1]Date of birth (1995-12-05) 5 December 1995 (age 24)[2]Place of birthMassy,
FranceHeight1.81Â m (5Â ft 11Â in)[3]Playing position(s)ForwardClub informationCurrent
teamManchester UnitedNumber9Youth career2001–2009CO Les Ulis2009–2012LyonSenior
careerYearsTeamApps(Gls)2012–2013Lyon B11(5)2013Lyon3(0)2013Monaco
B4(3)2013–2015Monaco49(11)2015–Manchester United143(51)National team‡2010–2011France
U1617(9)2011–2012France U1713(9)2012–2013France U184(3)2013France U195(0)2013–2015France
U2112(4)2015–France18(1) Honours Representing  FranceMen's footballUEFA European
ChampionshipRunner-up2016 France Senior club appearances and goals counted for the domestic
league only and correct as of 21:16, 16 July 2020 (UTC)‡ National team caps and goals correct
as of 27 March 2018
Issue resolved.
option1:
using repalce statement that parsed JSON escape charatacter has been removed from the string.
An now the display it exactly in table format.
option2:
concatenate and tag then at the end close tag .
Then it is coming as a table.

Send data from SerialPort to socket.io

I'm struggling with socket.io, express, and node.js.
I send data from an Arduino to my cmd. This is done with the serialport libary. But now I want this data displayed on my web browser. I'm using the express library for this. I have index.js here is the connection with the arduino and browser. And an index.html
This code do I have:
code from index.js (node.js server):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', console.log);
The data what is recieved from the serialport (Arduino), had to be displayed in the index.html (webbrowser). I tried already something but it doesn't work. It has to be printed in the <p></p> in the html code.
The index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="text">
<p></p>
</div>
<script>
var text = document.getElementById('text');
var socket = io.connect('http://localhost:8888');
socket.on('data', function(message) {
text.innerHTML = message.data;
});
</script>
</body>
</html>
Instead of
parser.on('data', console.log);
Try this:
parser.on('data', function (data) {
io.emit('data', { data: data });
});
That should send the parsed data from the SerialPort to the socket, which should end up on the client side on the website.

I receive a GET error when trying to serve html page with image using Node.js

I am new to Node.js and am unable to find a way to solve my issue. I have written a server using Node.js to serve a html webpage. The problem is that it wont display the images that are in the same folder. I am trying to serve my webpage as well as my images and css file. Any help would be appreciated.
Relevant code:
server:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
I recommend use app.use(express.static(__dirname + '/FOLDER_NAME')) in order to expose a folder to serve static files to the client. Here is the documents about serving static files using express.
Edit: Here is a simple working example of serving a index.html using express
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});

AJAX request on Node.js server

I am unable to make an AJAX request from my .html page to my node.js server for a JSON file. I've been reading on AJAX requests, but all I am able to make out is how to display the servers responseText.
It would be great if you could help me out, it would be even better if you could link me some tutorials on this, anyway this is what I've got at this moment:
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/test', function(req, res){
var arr = new Array();
var rd = readline.createInterface({
input: fs.createReadStream('info.json'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
arr.push(line);
}).on('close', function(){
res.send(arr);
});
});
app.get('/', function(req, res) {
fs.readFile('test2.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.listen(process.env.PORT || 3000);
test.html
<html>
<head>
<script>
function sendAjax(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText);
}
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
}
xmlHttp.open("GET", "/test", true);
xmlHttp.send();
}
</script>
</head>
<body>
<input type="submit" onClick="sendAjax()" value="SendAjax" />
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
</body>
</html>
I know this may not look like much, I've been struggling with this, and the book I have (Node.js in Action) doesn't help me alot. But as I said, what I want is to display the .json info in the browser. Thx for reading
If I understand right, you may replace
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
with
var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
You may also try to replace
res.send(arr);
with
res.json(arr);
Update
Or maybe you just forgot to write this line in the beginning of server.js:
var readline = require('readline');