Trouble using GET for a json file in node js - javascript

I'm new to REST api's and javascript in general and I'm having trouble using GET to retrieve a json file and display it in a browser. I'm only running my api as a localhost for now. I can get my server running but just can't get my json file to display. Below is my code, I have tried different things with the responce but have had no luck with getting it to work. Everything I've tried with it has displayed errors. Both this file and the json file are in the same folder. If someone knows what I need to put for instead of the //responce() it would be greatly appreciated. Thanks!
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
app.get("/userget", function(request, responce){
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('database.json', 'utf8'));
//responce()
});

If you have your javascript object, try:
res.status(200).json({
your_javascript_object
});

Put this instead for your /userget route.
```
res.setHeader('Content-Type', 'application/json');
var fs = require('fs');
res.send(JSON.parse(fs.readFileSync('database.json', 'utf8')));
```

Related

Chat application using socket.io over https

I've been working on a chat application using node.js and socket.io . I'm trying to run it over https .I'm a newbie in node.js and socket.io so please bear with me . Every help will be highly appreciated. I follow the instructions from here : http://kaworu.jpn.org/javascript/node.js%E3%81%AB%E3%82%88%E3%82%8BHTTPS%E3%82%B5%E3%83%BC%E3%83%90%E3%81%AE%E4%BD%9C%E3%82%8A%E6%96%B9
but i get this error :
GET https://mydomain.link:3000/socket.io/?EIO=3&transport=polling&t=1502934404775-5 net::ERR_INSECURE_RESPONSE
here is the code
server.js
var https = require('https');
var fs = require('fs');
var ssl_server_key = 'server_key.pem';
var ssl_server_crt = 'server_crt.pem';
var port = process.env.PORT || 3000;
var options = {
key: fs.readFileSync(ssl_server_key),
cert: fs.readFileSync(ssl_server_crt)
};
https.createServer(options, function (req,res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end("Hello, world\n");
}).listen(port);
clientside (chatnew.js)
$(function(){
var socket = io.connect('https://mydomain.link:3000');
});
Thank you in advance !

Local node.js server GET error when trying to load an HTML file

Quite new to this. I have the below node sever that runs locally on my machine. In index.html page I made a XMLHttpRequest to some web API, and my browser will be redirected to a url that starts with 10.200.100.200:8080/auth(suppose 10.200.100.200 is my IP)
The problem is that, currently a GET request to http://10.200.100.200:8080/auth returns an empty response. It doesn't work either when I paste that url to browser. What am I doing wrong with that node server? The index page seems to be working ok. Many thanks for your help!
node server:
var fs = require('fs');
var http = require('http');
var https = require('https');
var request = require('request');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var path = require('path');
var express = require('express');
var app = express();
var certificate = fs.readFileSync( 'something.0.0.1.cert' );
var privateKey = fs.readFileSync('something.0.0.1.key');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.use(express.static(__dirname+'/public'));
app.get('/auth', function(req, res) {
res.sendFile(path.join(__dirname + '/public'+ '/html'+'/authCode.html'));
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public'+ '/html'+'/index.html'));
});
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(8080,'0.0.0.0');

issue child process inside a server on node.js

I have an executable library in C (sudo ./ads1256_test adc.txt) where data are acquired from an ADC, likewise these data are automatically save in a text file (adc.txt).
On the other hand, I have a server in node.js (see code) in which would like to execute this program when a button in the website is pressed. For this, I tried to implement this process using the child process .exec('sudo ./ads1256_test adc.txt') but it did not work. It apparently runs but the values saved in the file are always zero. That is totally different to the obtained result when I execute the same command in terminal. I would appreciate if anybody could help me.
//Importing the core modules
var express = require('express');
var path = require('path');
var sys = require('sys');
var fs = require('fs');
var util = require('util');
var sleep = require('sleep');
var app = express();
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
//Static Directories
app.use(express.static(__dirname + '/public'));
app.post('/test', function (req, res) {
exec('sudo ./ads1256_test adc.txt');
});
//Server Starting
var server = app.listen(8080, function(err){
if(err){
console.log('Error starting http server');
} else{
console.log('Sever running at http://localhost:8080 ');
}
});
first thing first, fix your code to
- asynchronously handle the cp spawn
- show errors
Example with tree, may you adapt it to your binary and check the response, it should help you go forward.
app.post('/test', function (req, res) {
var cp = spawn('tree', []);
cp.stdout.pipe(res);
cp.stderr.pipe(res);
cp.on('close', function () {
res.end();
cp.stdout.unpipe();
cp.stderr.unpipe();
});
});

(crypto.js) TypeError: Data must be string or buffer

I am currently using crypto.js module to hash things. It was working for a while then I started getting this error:
Here is the foundation of my server:
process.stdout.write('\033c'); // Clear the console on startup
var
express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
path = require("path"),
colorworks = require("colorworks").create(),
fs = require("fs"),
crypto = require("crypto");
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
http.listen(443, function(){
// Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.
console.log("NJ project webserver is running on port 443.");
// Notify the console that the server is up and running
});
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response){
response.sendFile(__dirname + "/public/index.html");
});
I am aware that these functions are creating the problem:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
The problem being, if these functions don't work (which they don't anymore), roughly 200 lines of code will go to waste.
This error is triggered by attempting to hash a variable that does not exist:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.
What kind of data are you trying to hash ? Where does it come from ?
I would check the value of msg first then I would try :
crypto.createHash('md5').update(msg.toString()).digest('hex');
You could also use these packages instead:
https://www.npmjs.com/package/md5
https://www.npmjs.com/package/js-sha256

Why the node.js script is call twice?

I am a beginner in Node.js
I write the first script in Node.js like the below:
var count = 0;
var http = require('http');
var serv = http.createServer(function (req, res) {
count++;
console.log("why two?:" + count);
res.writeHead(200,{'Content-Type': 'text/html'});
require('colors');
if (count % 2 == 0) {
console.log('count:' + count);
console.log('smashing node'.rainbow);
res.end('<marquee>Smashing Node</marquee>');
} else {
console.log('count:' + count);
console.log('WTF'.rainbow);
res.end('<h4>Smashing Node</h4>');
}
});
serv.listen(3000);
Then I run this script
node first.js
In browser, access http://localhost:3000
And the result in console is:
why two?:1
count:1
WTF
why two?:2
count:2
smashing node
Why the code is called twice?
Thanks
Because two requests are being made.
Probably one is for / and the other is for /favicon.ico.
Your code doesn't care what the path is when it handles a request.
You can test that by looking in the Net tab of your browser's developer tools or examining the contents of the req object.
That anonymous function is called whenever you request on http://localhost:3000
So maybe somehow you're requesting twice (e.g. for / and /favicon.ico)
Try opening chrome dev tools, and in console tab you'll maybe see an error, that favicon.ico wasn't found.
or you can use morgan to keep track of requests:
var app = require('express')();
var morgan = require('morgan');
app.use(morgan('dev'));
It will log every request, with codes and URL-s. It needs express though.
var count = 0;
var http = require('http');
var serv = http.createServer();
serv.on('request',function(req,res){
count++;
console.log("why two?:" + count);
res.writeHead(200,{'Content-Type': 'text/html'});
if (req.url=='/') {
console.log(req.method);
console.log(req.headers);
console.log(req.url);
res.end('<marquee>Smashing Node</marquee>');
}
});
serv.listen(3000);
in this it checks only for the '/' url and then responds....so the marquee is returned

Categories