Accessing server values in javascript file? - javascript

EDIT: Forgot a piece of code when taking stuff that was relevant
I want to work with the "jsonData" value from my server in my javascript file, but i don't know how to get the values there?
server code:
var express = require('express');
var app = express();
app.use(express.static('public'));
var Amadeus = require('amadeus');
app.set('view engine', 'ejs');
app.listen(8080);
app.get('/hotels', function(req, res){
var searchTerm = req.query.cityCode;
amadeus.shopping.hotelOffers.get({
cityCode: searchTerm
}).then(function(response){
var jsonData = JSON.parse(response.body);
var output = "";
for(var i = 0; i < jsonData.data.length; i++){
output+= "Name: " + JSON.stringify(jsonData.data[i].hotel.name) + "\t";
output+= "Rating: " + JSON.stringify(jsonData.data[i].hotel.rating) + "\t";
}
res.render('pages/onestar', {jsonData: output});
}).catch(function(error){
console.log(error.response); //=> The response object with (un)parsed data
//console.log(error.response.request); //=> The details of the request made
console.log(error.code); //=> A unique error code to identify the type of error
});
});
JavaScript attempt that i have so far:
$(document).ready(function(){
$('#searchbutton').submit(function(){
event.preventDefault();
$.get('xxxxxx', function(jsonData){
console.log(jsonData);
});
return false;
});

You need to send something back from your express server program to the web browser. There are lots of methods on the res object to do that.
Replace
var jsonData = JSON.parse(response.body);
with
res.status(200).json(JSON.parse(response.body))
You could also send back the JSON text in the response.body directly rather than parsing it first, only to tell express to stringify it again. But the req.json() function also sets the Content-Type header on the response to the web browser so it knows it's getting JSON. With respect, that's a little complex for your apparent present level of understanding. Keep it in mind for a later optimization when you get your code working.

Related

Document is not defined on node.js - How can i import a variable from another .js file to node.js server?

Edit: Actually, my problem is "How to use "value" from selection.js in the server.js ? " I want to direct user to a searching page according to his/her choice .
i am new at web programming. I have server.js and a selection.js.
server.js is a node file, and my server is in it. selection.js is my item class changer. I am changing selected item's class with selection.js and i am trying to use this selected item from server.js. When i try below codes, i am taking this shit: Document is not defined on node.js
It is really painful. I am trying to solve it about hours. But, nothing!
Pls, help me :/
selection.js :
var iconContainer = document.getElementById('iconContainer');
var icon = iconContainer.getElementsByClassName("item");
for (var i = 0; i < icon.length; i++) {
icon[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
const btnSearch = document.querySelector("#btnSearch");
btnSearch.addEventListener("click", () => {
// get the active item's value
const value = document.querySelector(".item.active span").innerText;
console.log("value: ", value);
// do fetch
});
});
}
module.exports={searchPath: "/"+value};
server.js:
var fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
app.use('/public', express.static(path.join(__dirname, 'public')));
// '/' girdisi için index.html getirilecek.
app.get('/', function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
//---------------------------------------------------
// Server kuruyoruz.
var server = app.listen(8081,"127.0.0.1", function () {
var host = server.address().address;
var port = server.address().port;
console.log('Server http://' + host + ':' + port+' adresinde çalışıyor...');
});
var search = require('./public/js/selection');
console.log(search.searchPath);
So, the code you label as selection.js needs to be in your web page, either directly embedded or linked from a <script> tag so it can run in the web page in the browser.
Then, that code can make an Ajax call using the XMLHttpRequest or fetch() interfaces in the browser to a route on your server and pass the desired value.
That route on your server (which you need to define and add code for) can then examine that value and decide what data to return the the Ajax call.
Your Javascript in the web page, then receives that returned data from the Ajax call and decides what to do with it such as insert new content in the page for the user to see, cause the browser to load a different page or refresh the current page or whatever else is appropriate.

Get body of post request vert.x javascript verticle

Pasted below is the code of my javascript verticle which is deployed successfully. Since I couldn't find a way to debug the js verticle, I printed all the properties of the routingContext for reference. I am trying to get body of the request, however all the functions starting with getBody are returning null. I have pasted the request I am making below the code, with the log printed in the intellij terminal. Am I doing something wrong?
JS Verticle Code
var Router = require("vertx-web-js/router");
var server = vertx.createHttpServer();
var router = Router.router(vertx);
function writeHelp(obj) {
var txt = "";
for (var x in obj){
txt += x + "->" + obj[x] + "\n";
}
return txt;
}
router.post("/provider").handler(function (routingContext) {
var response = routingContext.response();
var json = routingContext.getBodyAsString();
response.putHeader("content-type", "text/plain");
//console.log("Helper\n" + writeHelp(routingContext));
//console.log("Request=" + writeHelp(routingContext.request()));
console.log("body=" + json);
response.end("Success");
});
server.requestHandler(router.accept).listen(8890);
POST Request made through ARC
Log from Intellij
Router: 257219241 accepting request POST http://localhost:8890/provider
Route matches: Route[ path:/provider pattern:null handler:io.vertx.core.Handler$$NashornJavaAdapter#69b539e failureHandler:null order:0 methods:[POST]]#32182409
Calling the handler
body=null
You have to add the BodyHandler to get parsed body:
From the official documentation:
var BodyHandler = require("vertx-web-js/body_handler");
// This body handler will be called for all routes
router.route().handler(BodyHandler.create().handle);

(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

Express.js and form validation

I'm tring to create a simple node- with express.js script that will sum 3 numbers.
On index I have this:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='/')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
#result
and also i'm now writing the serverside - app.js with req and res object but how to return a result... also result = 1id + 2id + 3id
app.js
var express = require('express');
app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var i = req.param('1', null);
var j = req.param('2', null);
var k = req.param('3', null);
var r = i+j+k;
res.send(r);
});
How I to send results (r) into div id Result on index.jade... so how to return result to index.jade
also here is pastebin code: http://pastebin.com/J9MRFCaE ... i'm new to node and express and sorry for stupid question...
It's simple, just call your "index.jade" rendering passing your data (instead of 'res.send(r);') :
res.render('index', {
result: r
});
And display "result" variable in your jade file :
#result #{result}
Additional information on jade code and express rendering

Categories