Get Request for RESTful service not working - html

I'm trying to use a restful service to access data that is posted to a MongoDB cluster. My problem is that I can't even connect to the service, the get request doesn't seem to be working. Console.log("test")is not reached and I'm met with a blank console, so I don't think the readystate is changing.
I've done a ton of troubleshooting and found that the link works on its own (https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items) and displays the data when pasted into the search bar. I've also tried changing browsers and even compared to my friend's code which works and STILL I can't even seem to connect.
I'm sure it's just some dumb little mistake but I'm completely at a loss here so any help is MUCH appreciated!
File with get request. I edited out the username. 'item' is the name of the MongoDB cluster.
<html>
<head>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && this.status == 200) {
console.log("test"); //NOT REACHED
var responseObj = JSON.parse
(xhttp.responseText);
};
}
//PROBLEM HERE
xhttp.open("GET", "https://RESTfulServiceExample.[REPL.IT USERNAME].repl.co/items", true);
xhttp.send();
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js">
</script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
RESTful Service:
Index.js: (edited out username and password of mongodb.
var express = require('express'); // control-shift-S to bring up shell in repl.it and npm
install express / other packages
var app = express();
var port = 5000; // the port is automatically routed by the repl.it domain
mongoose = require('mongoose');
Item = require('./model/model.js');
bodyParser = require('body-parser');
mongoose.Promise = global.Promise; // for asynchronous callbacks
mongoose.connect('mongodb+srv://[USERNAME]:[PASSWORD]#cluster0.thmkp.mongodb.net/Pokemon?
retryWrites=true&w=majority');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./routes/routes'); //importing route
routes(app); //register the route
app.listen(port);
Routes.js
'use strict';
module.exports = function(app) {
var itemList = require('../controllers/controller');
app.route('/items')
.get(itemList.list_items)
.post(itemList.create_item);
app.route('/items/:id')
.get(itemList.get_item)
.put(itemList.update_item)
.delete(itemList.delete_item);
};

Try to change
if (this.readyState == 4 && this.status == 200) {
// your code block
}

Related

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.

valid json format gives error “<“ while parsing also view engine error 500 using mean stack angular 2+

Mean server with angular 2+.
I have a dataservice.js that requests a get to the server, to receive a json response from the http://localhost:3000/server/routes/api/test.js
This gives me an error 500 view engine not selected,
My understanding is angular doesn’t require a view engine? As the angular/ browser takes care of that.
Somehow the routing doesn’t seem to work when I do a getter to the api.
The angular routes work with the html components, but via the dataservice a get request to the mongodb doesn’t work either. The get/test most often returns error 500 no view engine selected as well.
If it does return something, it returns an error message “<“ not in jsn format.
How do I make sure that the routing works for my get and post messages and they are returned back in json format and not in HTML.
And how do I figure out that it uses the correct routing? I somehow doubt that the rouitng for the get/ post messages seem to use express rather then the angular modules
I am quite new to stack overflow/ Mean server so if you require more info please let me know.
FYI
I have been able to get a json file from the server (not the database) via a get. This worked. So why is it that a get to the database doesn’t seem to work and the same question about why I can’t seem to get a json response from the http://localhost:3000/server/routes/test/api.js in the api.
I spent a full 2 days troubleshooting to no result.
in my api.js
router.get ('/test', function (req, res, next) {
res.json({'testMessage': 'everything is going ', 'someNumber': 457});
});
In the server.js
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require ('morgan');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var chat = require('./server/routes/chat');
var app = express();
var passport = require ('passport');
var cookieParser = require ('cookie-parser');
var session = require ('express-session');
var config = require ('./config/database');
var engines = require('consolidate');
var mongoose = require('mongoose');
var router = express.Router();
// this is where I set up the routing for the api
// in the root of the project I created server directory and
// within it a routes directory that holds the api.js
var api = require('./server/routes/api');
mongoose.Promise = require ('q').Promise;
require('./config/passport')(passport);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(morgan('dev'));
app.use(session({
secret: 'secret123',
resave: true,
saveUnitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//this is where I set up the routing is something wrong here?
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use('api', api);
thx everyone, I moved
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
below
app.use('api', api);
and changed it to:
app.use('/api', api);
Problem solved, if app.get('*') is read first it will send all requests to index.html instead. So make sure any other routings go above it.

How to display connected clients using node.js and socket.oi.js on HTML

I am new with node.js and socket.io i was able to start a local server via node.js and get the numbers of client connected on port 3000 using console.log now my next step is displaying it on my HTML, i was reading about how to include socket.io.js on HTML and tried the on('connect') method but its returning a undefined error , Any advice would be great thanks in advance!
My server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('listening to port 3000, server is running..');
app.get('/', function (req,res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
On my index.html
//This is located on my html head tag
<script src="http://localhost/socket.io/socket.io.js"></script>
<div class="col-lg-12">
<h1 id="users"></h1>
</div>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('connect',function(){
$('#users').html = socket.users.length;
));
</script>
I manage to display the numbers of connected users on client side by emitting a event than client will receive and display it.
revised my server.js
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//added this below
io.sockets.emit ('totalUsers', {count: connections.length});
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
//added this below
io.sockets.emit ('totalUsers', {count: connections.length});
});
Then on my index.html
socket.on('totalUsers', function(data){
console.log(data.count);
$users.html('Total connected users: '+data.count);
});
You must include or link your socket.io.js before the io.connect() on your html. like this
<script type="text/javascript" src="assets/nodejs/node_modules/socket.io-client/dist/socket.io.js"></script>
you can use this cdn
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js
but it is better to use your socket.io.json your local folder it is in the node_modules/socket.io-client/dist/socket.io.js if you are using latest version of node.
Hope it will help.

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');

Displaying streaming twitter on webpage with socket.io/node.js

I'm trying to build a Twitter streaming web application using node.js socket.io and twit.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
io.sockets.on('connection', function (socket) {
console.log('Connected');
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
T.stream('statuses/filter', { track: watchList },function (stream) {
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
console.log(tweet.text);
});
});
});
Here's my client side
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('tweet', function(tweet) {
$(
'<div class="tweet">' + tweet.text + '</div>');
});
});
</script>
</div>
When I run node app.js and try to connect to localhost:8080 I just get a blank page, even if everything ( soket.io, jquery, ... ) seems to have loaded correctly.
Here's a sample of the server output :
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized pwH0dbx4WvBhzSQXihpu
debug - setting request GET /socket.io/1/websocket/pwH0dbx4WvBhzSQXihpu
debug - set heartbeat interval for client pwH0dbx4WvBhzSQXihpu
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"stream","args":["RT #mintycreative: Great to chat today RT #SharonHolistic: Treatments available tomorrow http://t.co/5Poq3KU08u Book yours now #WestMidsHou…"]}
debug - websocket writing 5:::{"name":"stream","args":["RT #laurenpeikoff: #BREAKING #ScottsdalePD confirms - police are investigating Michael Beasley for alleged sexual assault. #12News #azcentr…"]}
Hope you can help me to correct my mistakes.
Problem solved
Here's the code without any mistakes : (server side)
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
io.sockets.on('connection', function (socket) {
console.log('Connected');
var stream = T.stream('statuses/filter', { track: watchList })
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
});
});
});
(client-side)
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('stream', function(tweet){
$('#tweetd').append(tweet+'<br>');
});
</script>
<div id="tweetd"></div>
</div>
The first issue is that you are constructing a new twitter listener each time a socket connection is opened. You should move that outside of the connection event. This is likely not ideal. I'm not sure how the twitter module is handling that internally but it likely actually is creating a new connection to their API each time a websocket connects.
On the client side you jQuery could bit a bit different. If you just wanted to add a tweet to the page each time a tweet occurs, append a new tweet to the body element with $('body').append()
See this gist for reference.