I have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});
Related
this issue has been boggling my mind for days. There's nothing noticable to me that I have done, but my node port produces an insecure socket, while my site itself is completely secure (ssl). So mathtutortime.com is secure, but this is the error I get when I go to https://www.mathtutortime.com/account/get_tutoring/lobby.php:
I tried reinstalling my ssl certificate, as well as ensuring my ssl certificate isn't expired, but to no avail. I have also gone to the actual part of my site in node having this issue, and it indeed is not secure :( Even though mathtutortime.com IS.
Here's my code for lobby.php:
gather data for site, then create a post request
<script src="https://mathtutortime.com:3001/socket.io/socket.io.js"></script>
<script>
var BACKEND_URL = 'https://mathtutortime.com:3001';
var SESH_END_INCORRECT = 'https://mathtutortime.com/account/get_tutoring/done_incorrect';
var SESH_END_CORRECT = 'https://mathtutortime.com/account/get_tutoring/done_correct';
var name = "<?php echo $_SESSION["username"]?>";
var pass = "<?php echo $_SESSION["password"]?>";
var time = 0;
var role = 'tutor';
$.post(`${BACKEND_URL}/requestWhiteboard`, { name, time, role, pass }, function(res){
window.location.href = `${BACKEND_URL}/whiteboards/${res.whiteboardId}`;
</script>
And here's my server in node:
var fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var all;
var options = {
key: fs.readFileSync('./privatekey.key'),
cert: fs.readFileSync('./certificate.crt'),
requestCert: false,
rejectUnauthorized: false
};
const chat_port = 3001;
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
var server = require('https').createServer(options, app);
require('https').globalAgent.options.rejectUnauthorized = false;
var io = require('socket.io').listen(server);
app.post('/requestWhiteboard', function(req, res){
...
}
app.get('/socket.io.js', function(req, res){
res.sendFile(__dirname + '/socket.io.js');
});
var host = '45.79.111.96';
server.listen(chat_port, host, function(){
console.log('listening on *' + chat_port);
});
Also, socket.io.js is in my directory (referenced in an app.get below)
Thanks for any ideas!
I have a simple setup where I have some draggable divs and I want to use sockets.io to update the position between clients.
On my client (index.html) I have :
// find the elements
var elements = document.getElementsByClassName('ball'),
labelsX = document.getElementsByClassName('coords-x'),
labelsY = document.getElementsByClassName('coords-y');
// loop over the 3 items...
for (var n = elements.length; n--;) {
// ... augment our default options with individual `onDrag` handlers
var opts = {
onDrag: onDragFactory(n),
setCursor: true
};
// ... and initialize drag for each
window.d = new Draggable(elements[n], opts);
console.log('ddd');
}
// bind `n` to its value at iteration time
function onDragFactory (n) {
return function (element, x, y) {
//This doesnt seem to work
console.log(elements[n].style.top);
socket.emit('positionx', elements[n].style.top);
socket.on('positionx', function(positionx){
elements[n].style.top= positionx.value();
});
}
}
My server is then :
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
//Server Side Listen for an event from the client
io.on('connection', function(socket){
socket.on('positionx', function(positionx){
console.log('recieving');
console.log(positionx);
io.emit('positionx', positionx);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
The server however doesn't seem to receive any information. Is there something I'm doing wrong? Any help would be much appreciated!
In your client you need to define socket.
var socket = io();
Also, make sure you are including socket.io-x.x.x.js prior to calling socket.io in your javaScript. You are probably already doing this, but it's unclear without seeing more code.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//PROBLEM LINE
**app.use(parser.json);**
///////////////
var todos = [];
var nextTodoItem = 1;
app.use(bodyParser.json);
app.get('/', function(req, res){
//console.log("ToDo Root");
res.send("ToDo Root");
});
//GET REQUEST TO GET ALL TODO ITEMS
// GET /todos
app.get('/todos', function (req, res) {
// Need to send back the array of todos
res.json(todos); //array is converted to JSON.
}
);
//GET REQUEST TO GET SOME SPECIFIC TODO
//GET todos/:id
//Express uses : (colon) to parse data.
app.get('/todos/:id', function (req, res) {
var todoID = parseInt(req.params.id, 10);
var todoObjectWithID = -1;
todos.forEach(function (todo) {
if(todo.id == todoID){
todoObjectWithID = todos[todoID - 1];
}
});
if(todoObjectWithID == -1){
res.status(404).send();
} else {
res.json(todoObjectWithID); //Send the JSON of the specific todo with id requested.
}
console.log('Asing for todo with id of ' + req.params.id);
});
//Create a POST request to create new TODO Items.
//POST /todos
app.post('/todos', function(req, res){
var body = req.body;
console.log("description");
res.json(body);
});
//Server basic start up (port and log)
app.listen(3000, function () {
console.log("Server up and running");
});
I run the server with bash (Mac OS) but I go to http://localhost:3000 nothing loads, but when I remove the app.use(bodyParser) it loads properly.
What is the problem in the body-parser?
This problem only occurs when I have that line, otherwise, the server runs up perfectly fine. I need that parser though, so what is my option?
Change that line to app.use(bodyParser.json());
So i have found an api for node https://github.com/schme16/node-mangafox
But i have no idea on how to use it
Lets say that i want to use this
mangaFox.getManga = function(callback){
$.get('http://mangafox.me/manga/',function(data){
var list = {};
data.find('.manga_list li a').each(function(index, d){
var b = $(d);
list[mangaFox.fixTitle(b.text())] = {id:b.attr('rel'), title:b.text()};
});
(callback||function(){})(list);
}, true);
}
What should i do to show the list in the '/' route
This i what i have so far
var express = require('express'),
path = require('path'),
mangaFox = require('node-mangafox');
var app = express();
app.get('/', function(req, res) {
});
app.listen(1337);
console.log('oke');
If some cloud help me understand how this works
app.get('/', function(req, res) {
function renderList(data) {
return Object.keys(data);
res.send(JSON.stringify(list));
}
var list = mangaFox.getManga(renderList);
});
This is the simplest thing I can come up with. You just get the object returned by the module, list its keys, and send back that stringified as your response. Try it out. You'll probably want to replace the renderList with some HTML templating.
I really hope to find some answers here as i tried everything by now.
Background:
Overtime we deploy code to web server, we need to do a cache warm up, i.e. access the site and make sure it loads. First load is always the slowest since IIS require to do some manipulations with a new code and cache it.
Task:
Create a page which will a checkbox and a button. Once button is pressed, array of links sent to server. Server visits each link and provides a feedback on time it took to load each page to the user.
Solution:
I am using node JS & express JS on server side. So far i manage to POST array to the server with links, but since i have limited experience with node JS, i can not figure out server side code to work.
Here is a code i got so far (it is bits and pieces, but it gives an idea of my progress). Any help will be greatly appreciated!!!
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false});
var http = require("http");
function siteToPrime(url){
http.get(url, function (http_res) {
// initialize the container for our data
var data = "";
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
};
//Tells express where to look for static content
app.use(express.static('public'));
app.post('/', parseUrlencoded, function(request, response){
var newBlock = request.body;
console.log(Object.keys(newBlock).length);
var key = Object.keys(newBlock)[0];
console.log(newBlock[key]);
siteToPrime("www.google.com");
response.status(201);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
Assuming that you have access to the array in the post route:
var express = require("express"),
request = require("request"),
app = express();
var start = new Date();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
function siteToPrime(req, res, urls) {
urls.forEach(function(url)) {
request(url, function(error, res, body) {
if (!error && res.statusCode == 200) {
console.log(url +' : ' + body);
console.log('Request took: ', new Date() - start, 'ms');
}
});
}
res.redirect('/');
};
app.post('/', function(req, res){
var urls = req.body.urls // Array os urls.
siteToPrime(req, res, urls);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});