Ok guys, when I run my code with node.js and try to open the port on Chrome I get the error "Cannot Get /" instead of rendering the form . There are several questions on this, here but unfortunatly none helps. It would be great if you could take a look at the code and maybe state the problem.
Also here what I am trying to do : I am using import.io to take some data from trip advisor, which comes to me as JSON objects. Then I want to use a form to filter the names of the places, and give the user what he wants.
I know import.io is in beta and not a popular tool yet but it I believe problem is not caused by it as if I just print out the data using console.log it prints out well. So the problem you be with taking the request or rendering the html i think
Here is the html :
<html>
<head>
</head>
<body>
<form action="example2.js" method="get">
<input type="radio" name="catagory" value="Church"> Church </br>
<input type="radio" name="catagory" value="Piazza"> Piazza </br>
<input type="radio" name="catagory" value="Basilica"> Basilica </br>
<input type="submit" name="Submit"> Submit
</form>
</body>
</html>
And here is the JS document for Node.js
var http=require('http');
var importio = require("import-io").client;
var io = new importio("19781bd4-6f35-405f-88ef-2f3819b42d9c", "T7Twn5JRXweKI9/9bQ5MSdXMpwUTdYsNgFcJQKTj0b8qKea960gm1R/Tf/EMMYhMUzyLVbNFlf1gZ/rLK2bpZA==", "import.io");
var express = require('express');
var app= express();
var bodyParser= require('body-parser');
var data = [];
var runningQueries = 0;
// Make sure that you have connection with import.io
io.connect(function(connected) {
if (!connected) {
console.error("Unable to connect");
return;
}
// Callback for handling the message from import.io
var callback = function(finished, message) {
if (message.type == "DISCONNECT") {
console.error("The query was cancelled as the client was disconnected");
}
if (message.type == "MESSAGE") {
if (message.data.hasOwnProperty("errorType")) {
console.error("Got an error!", message.data);
} else {
console.log("Got data!", message.data);
data = data.concat(message.data.results);
}
}
if (finished) {
console.log("Done single query");
runningQueries--;
if (runningQueries <= 0) {
runningQueries = 0;
console.log(data);
console.log("All queries completed");
for(i=0; i<data.length ; i++){
console.log(data[i].name)
}
}
}
}
//HANDLING REQUEST
app.use(bodyParser());
app.get('/example2.js',function(request, response){
var typeplace = request.body.catagory;
for(i=0; i<data.length ; i++){
if((data[i].name).indexOf(typeplace) === -1){
data.splice(i, 1);
}
}
})
runningQueries += 2;
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
});
app.listen(8000);
Sorry if my code if unreadable because of hanging parents etc.
Thanks in advance.
It seems you don't have a (GET) route defined for /, at least in the code you've provided.
It seems there is no place in your node js code where you render the "/" page. Since it looks like you are using express already, try the following:
app.get('/', function(req, response) {
response.render('YOUR HTML FORM FILE NAME');
});
Related
I need to give var into my html like server -> client
I'm not good at english and this situation is hard to explain so i will show you the code
html (index.html):
<script type="text/javascript">
console.log(tmp) //lol!
</script>
node.js:
fs.readFile('./index.html', (err, html) => {
if (err) {
response.statusCode = 404;
response.end(`error!`);
}
else
{
tmp="lol!"
response.write(html);
response.end();
}
});
server should response and give value to client same time. but it didn't work.
i don't want use external modules like express.js or ajax anything need to download things as it's possible
could you help me?
fs.readFile('./index.html', (err, html) => {
if (err) {
}
else
{
var tmp = new Object();
tmp.string = "hello world!"
var go = JSON.stringify(tmp)
res.write(`<div id="data"><div id="list" data-list='${go}'></div></div>`);
res.write(html);
res.end();
}
});
HTML:
var data = JSON.parse(document.getElementById("list").getAttribute("data-list"));
alert(data.string);
make a div element and set attribute, then write in response.
I am using Node.JS with Express. The following line fails, and I need help fixing it.
var routines = require("myJsRoutines.js");
When I run index.html and click MenuItem, I get the first alert, but not the second one.
I have both files in the same directory. Thanks
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
MenuItem
<script>function myMenuFunc(level) {
alert("myMenuFunc1:" + level);
var routines = require("myJsRoutines.js");
alert("myMenuFunc:2" + level);
routines.processClick(level);
alert("myMenuFunc:3" + level);
}</script>
</body>
</html>
myJsRoutines.js:
exports.processClick = function processClick (param1) {
console.log(param1)
}
Script in <script> tags only runs on the client, and script on the server never directly handles DOM events like clicks. There is no magical event wireup - you need to make them interact.
Assuming folder structure from http://expressjs.com/en/starter/generator.html
Updated module code, in /modules/myJsRoutines.js...
var myJsRoutines = (function () {
var multiplier = 2;
return {
processLevel: function (level, callback) {
console.log('processLevel:', level); // CLI or /logs/express_output.log
// validation
if (!level) {
// error is usually first param in node callback; null for success
callback('level is missing or 0');
return; // bail out
}
// processing
var result = level * multiplier;
// could return result, but need callback if code reads from file/db
callback(null, result);
}
};
}()); // function executed so myJsRoutines is an object
module.exports = myJsRoutines;
In /app.js, load your module and add a get method...
var myJsRoutines = require('./modules/myJsRoutines');
app.get('/test', function (req, res) {
var level = parseInt(req.query.level) || 0;
console.log('server level:', level);
myJsRoutines.processLevel(level, function (err, result) {
if (err) {
res.status(500);
return res.send(err);
}
res.send('result ' + (result || '') + ' from the server');
});
});
In /public/index.html, add client script to make an HTTP request to the get method...
<a class="test" href="#" data-level="1">Test Level 1</a>
<a class="test" href="#" data-level="2">Test Level 2</a>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function(){ // jQuery DOM ready
$('.test').click(function () { // click event for <a class="test">
var level = $(this).data('level'); // from data-level="N"
var url = '/test?level=' + escape(level);
console.log('client url:', url);
// HTTP GET http://localhost:3000/test?level=
$.get(url, function (data) {
console.log('client data:', data); // browser console
});
return false; // don't navigate to href="#"
});
});
</script>
...start the server from the command line...
npm start
...open http://localhost:3000/ in your browser, Ctrl+Shift+i to open the browser console, and click the links.
Run from a node server..var routines = require("myJsRoutines.js"); in the server.js file and Just call a javascript onclick function..and post parameters..for posting parameters..you'll be needing Ajax...and console log the data in node..or After sending the data to the node server..run the function in node server.
Code snippet for calling the function from a href..
and
`MenuItem
<script type="text/javascript">
function myMenuFunc('Level 1') {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
`
This line:
var routines = require("myJsRoutines.js");
fails because the require statement is a nodejs function. It does not work with the browser nor does it work with javscript natively. It is defined in nodejs to load modules. To see this
go to your command line and run this
> node
> typeof require
'function'
go to your browser console; firefox - press Ctrl + K
>> typeof require
"undefined"
To achieve your aim, there are two options that come to my mind
// Assumed Express server running on localhost:80
var express = require('express');
var app = express();
app.get("/myJsRoutines", loadRoutines);
app.listen(80);
Option I: XMLHttpRequest
This is a browser API that allows you to open a connection to a server and talk with the server to collect stuff using HTTP. Here's how you do this
<script>
var request = new XMLHttpRequest(); // create an xmlhttp object
request.open("GET", "/myJsRoutines"); // means GET stuff in there
request.link = link;
// wait for the response
request.addEventListener("readystatechange", function() {
// checks if we are ready to read response
if(this.readyState === 4 && this.status === 200) {
// do something with response
}
})
//send request
request.send();
</script>
Lookup XMLHttpRequest API or the new fetch API
Option II: Pug
Pug, formerly named jade is a templating engine for nodejs. How does it work? You use it to programmatically create the html on the server before sending it.
Lookup the site -> https://pugjs.org/
i know some persons asked this question before but i don't understand answers :/
I'm using node.js, and i realy want to use Ajax in it.
My code is :
var $ = require('jquery');
var http = require("http");
var ws = require("nodejs-websocket");
var fs = require("fs");
var colors = require('colors');
http.createServer(function (req, res) {
fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauDeJoueur = new Array();
var server = ws.createServer(function (connection){
connection.nickname = null
connection.on("text", function (str){
if (connection.nickname === null){
connection.nickname = str;
console.log((connection.nickname+" arrive sur PixelWorld !").green);
}
else{
var code = str.substring(0,2);
var reste = str.substring(2,str.length);
switch(code){
case "01":
var coupe = reste.split("4H[m~Ft7");
var mail = coupe[0];
var mdp = coupe[1];
$.ajax({
url: "fonctionPHP/connection.php",
type: "POST",
data: {'mail': mail,'mdp': mdp},
async:false,
success: function(html){
if(html == "OK"){
console.log("oui");
}
else{
console.log("non");
}
}
});
break;
case "02":
break;
}
}
})
connection.on("close", function (){
console.log((connection.nickname+" a quitté PixelWorld !").red);
})
})
server.listen(8081)
function broadcast(str) {
server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
My problem is at the line "$.ajax({".
The server notice me when a user is coming, it's ok. But when he send a message with a 01 code, node crash and say me :
$.ajax({
^
TypeError: Object function ( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
} has no method 'ajax'
at Connection.<anonymous> (/var/www/dhkuhnuhbnkiuh/app.js:46:8)
at Connection.EventEmitter.emit (events.js:95:17)
at Connection.processFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:516:9)
at Connection.extractFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:458:14)
at Connection.doRead (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:209:23)
at Socket.<anonymous> (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:52:8)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
Sorry if my English isn't good, I'm French and bad at English. :/
Thank you for your help :D
Doing a request from nodejs is fairly easy, dont have to use $.ajax at all. You can use the npm request module. $.ajax is built for firing requests from the browser. But if you 'really' want to use $.ajax on node, I think you can read through this question
First,we begin with understanding AJAX and Node.Ajax is a client-side xml-based technology that automatically updates contents of a web page, without the page having to reload. Node.js is a server-side scripting language.
To illustrate this clearly, we will create a client client.html file and a server server.js
Aside from having npm installed, we will install express middleware and some of it's dependencies that we are going to use.
npm install --save express body-parser body-parser-xml
Let's begin by writing our server.js file. This file is going to parse xml requests sent AJAX. After processing request body, server should then send response back to client.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
require('body-parser-xml')(bodyParser);
app.use(bodyParser.xml({
limit: '1MB',
XmlParseOptions: {
normalize: true,
normalizeTags: true,
explicitArray: false
}
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "client.html");
});
app.post('/library', bodyParser.urlencoded({ extended: false }), function(req, res) {
console.log(req.body);
var title = req.body.book.title;
var author = req.body.book.author;
var year = req.body.book.year;
console.log(title + " " + author + " " + year);
//optional operations like database can be performed here
// we are sending a response mimicking a successfull search query
res.end("Book Found in library");
});
var server = app.listen(8080, function() {
var host = '127.0.0.1';
var port = server.address().port;
console.log("Server running at http://%s:%s\n", host, port);
});
Next, create client.html file. This file will have simple form that when submitted call on an AJAX function that in turn sends xml data to server.js then waits and process response
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function Search() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.getAllResponseHeaders();
xmlhttp.open('POST', 'http://127.0.0.1:8080/library', true);
console.log(document.getElementById('title').value);
console.log(document.getElementById('author').value);
var text = "<book>" +
"<title>" + document.getElementById('title').value + "</title>" +
"<author>" + document.getElementById('author').value + "</author>" +
"<year>" + document.getElementById('year').value + "</year>" +
"</book>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
console.log("All ok. You hit the server");
}
}
};
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(text);
}
</script>
</head>
<body>
<form name="" method="POST" action="">
Title:<input type="text" name="title" id="title">
Author:<input type="text" name="author" id="author">
Year:<input type="text" name="year" id="year"><br>
<br>
<input type="button" value="Search" onclick="Search()" />
</form>
</body>
</html>
Hope this guide helps in future. Thanks
I have a tracking app built with Node that is accessed by other sites in our network. They will access the app thru the head of their html files like so:
<title>Test</title>
<meta name="generator" content="TextMate http://macromates.com/">
<script src="http://mynetwork.com:1337/tracker.js?pid=publisher1&ps=home"></script>
</head>
<body>
The tracker.js file uses socket.io to connect to app.js which stores some data in MongoDB. For some reason when start socket.io then load a page that references that Tracker.js scripts I get an error "Uncaught SyntaxError: Unexpected identifier" on line 1 which is actually the “Welcome to socket.io." message and not the javascript thats in the file.
Here is what Tracker.js looks like:
(function(document, onload){
var io = document.createElement('script');
io.src = "//cdn.socket.io/stable/socket.io.js";
io.setAttribute('async', 'true');
if ( typeof onload === 'function') {
io.onloadDone = false;
io.onload = function() {
io.onloadDone = true;
onload();
};
io.onreadystatechange = function() {
if ( "loaded" === io.readyState && !io.onloadDone ) {
io.onloadDone = true;
io.onload();
}
};
}
(document.getElementsByTagName('head') || document.getElementsByTagName('body'))[0].appendChild(io);
});
(document, function(){
var socket = io.connect('http://mynetwork.com:1337');
socket.emit('adTracker',
{ adServer: 'datalunk', adZone : 'top_home', referingURL : 'site.com' }
);
socket.on('entrance', function(){
console.log('Response is:' + data.message);
});
});
The app.js file looks like this:
var io = require('socket.io');
var tracker = io.listen(1337);
tracker.configure(function () {
tracker.set('authorization', function (handshakeData, callback) {
if (handshakeData.xdomain) {
callback('Cross-domain connections are not allowed');
} else {
callback(null, true);
}
});
});
tracker.sockets.on('connection', function (socket) {
socket.on('entrance', {message: 'connection has been made to app.js'});
socket.on('adTracker', function (data) {
var adRequestData = data;
var pass = ["bigbooks"];
var databaseUrl = "user:pass#linus.mongohq.com:10006/node-test";
var collections = ["mads"]
var db = require("mongojs").connect(databaseUrl, collections);
db.cmnads.insert({adRequest : adRequestData}, {$set: {password: pass}}, function(err, updated) {
if( err || !updated ) console.log("User not updated");
else console.log("User updated");
});
});
});
Can anyone tell me why I would be getting the socket.io welcome message & error on line 1 and how do I resolve it?
(function(document, onload){
var io = document.createElement('script');
// rest of code
});
(document, function(){
// rest of code
});
});
should be
(function(document, onload){
var io = document.createElement('script');
// rest of code
})(document, function(){
// rest of code
});
});
You use an anonymous function that you should call (and you don't do it).
the correct syntax is (for a more simple example):
(function(a) {console.log(a)})('Hello World');
However you do:
(function(a) {console.log(a)});
('Hello World');
Make sure that the server has the latest stable version of Node installed. According to the official web site, it is currently v0.8.16.
Also, if socket.io server is running on http://mynetwork.com:1337/ then I believe you should be able to include the socket.io.js from http://mynetwork.com:1337/socket.io/socket.io.js
The fastest way to check if maybe the Node version is the source of problem is to install Node Version Manager, then v0.8.16 and finally run the socket.io server again
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
nvm install v0.8.16
nvm use 0.8.16
node yourSocketIOserver.js
app.get('/',function(req,res){
res.render('home'); // I want the template to be able to access the flash message..
});
app.get('/go',function(req,res){
req.flash("info", "You went GO, and got redirected to home!");
res.redirect('/');
});
The user first goes to "/go". After that, he will be redirected to "/" and I want a flash message to show as a javascript alert.
How can I do that?
Add it as a local to your call to render:
res.render("home", {info: req.flash("info")});
And use it in your template:
#flash
p= info
You can use express dynamic helpers to make your life easier.
app.dynamicHelpers({flashMessages: function(req, res) {
var html = ""
, flash = req.flash();
['error', 'info'].forEach(function(type) {
if(flash[type]) {
flash[type].forEach(function(message) {
html += "<div class='alert " + type + "'>" + message + "</div>";
});
}
});
return html; }});
and in your layout (ejs example)
<body><%- flashMessages %><%- body %></body>
app.dynamicHelpers({flash: function(req, res){return req.flash();}});
Now you have access at the flash object in you view. No HTML in your logic and no need to add all the params in every routes.
For me, I use the following code to display flash message:
In app.js
app.use(function (req, res, next) {
req.session.message = req.session.message || { error: [], success: [], info: [] };
app.locals.message = req.session.message;
}
In your user.js route:
app.post('/users/new', function (req, res, next) {
//...
// do some work
req.session.message.info.push('Account created successfully');
res.redirect('/login');
});
Then, create a message.jade in view that you could be included into other views:
In message.jade
- var i
- if (message.error && message.error.length)
.alert.alert-warning.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.error.length; i++)
.center!= message.error[i]
- if (message.info && message.info.length)
.alert.alert-info.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.info.length; i++)
.center!= message.info[i]
- message.info = message.error = [] // REMEMBER to reset messages to an empty array
Had a similar issue, solution seems to be:
req.flash('error', 'validation failed');
res.redirect('back');
Using back seems to maintain the flash message, where as redirecting to the same route looses it.
If you're using Express 3, the built-in flash functionality has been removed. To get the same functionality, you'll want to install the connect-flash module, then add the code from this Gist just after you initialize your sessions and before app.use(app.router);: https://gist.github.com/3070950