nodeJS: Sending html data from one js to another - javascript

The code below is working
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB')
app.use('addUserToDB', addUserToDB)
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
However, when I try to remove the following method and place it into another .js file so I can get the firstName from that file. It's not working. The following code is in addUserToDB.js:
var addUserToDB = app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = addUserToDB;
I have tried making a addUserToDB.js file and added the code
var express = require('express')
var app = express();
app.get('addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
but it seems I am missing something because it doesn't work. Thanks.

A few things here. First, need to do a require of addUserToDB.js from server.js (I will assume that's the name of your main file) and then use it as a middleware. Also, you need to export the app from addUserToDB.js.
server.js:
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB');
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.use(addUserToDB);
addUserToDB.js:
var express = require('express')
var router = express.Router();
router.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = router;

Related

Passing array from js to Nodejs

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");
});

Trying to run a script with Express on localhost:3000

Stuck on my first attempt at a basic app. Scraper.js scrapes a URL and writes the returned array to the document obj when run alone in console, so that part works. Now all I want is an Express server to run the script whenever I open localhost:3000 but not sure how to do so.
|node_modules
|package.json
|public
|-index.html (boilerplate HTML. Not importing anything)
|src
|-scraper.js
|index.js
index.js:
var scraperjs = require('scraperjs');
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
app.listen(3000);
--
scraper.js:
scraperjs.StaticScraper.create('https://examplesite.com/')
.scrape(function($) {
return $(".entry-content p").map(function() {
var content = $(this).html();
return content
}
}).get();
})
.then(function(data) {
... // eventually will write the items returned from the data array to div's
}
});
You need to export the scraperjs function using module.exports = functionName() as the last line in scraper.js.
Your require in index.js needs to factor in the path location for scraper.js. So:
var scraperjs = require('./src/scraperjs');
Here is a one that i've coded with promises, and also using a global variable which is daNews
var scraperjs = require('scraperjs');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var url = 'https://news.ycombinator.com/';
var daNews;
function myScraper(){
return new Promise((resolve, reject) => {
scraperjs.StaticScraper.create(url)
.scrape(function($) {
return $(".title a").map(function() {
return $(this).text();
}).get();
})
.then(function(news) {
daNews = news;
resolve('done');
})
});
}
app.get('/', function(req, res){
async function m1(){
var x = await myScraper();
if(x == 'done'){
res.send(daNews);
}else{
console.log('err');
}
}
m1();
})
app.listen(3000);

Reactjs serever side stylesheet not working

I am using Reactjs server side. when I implemented style.css file in my project.
but when I run that project then It display error :
So,how can I resolve this. I also try fs: empty in my code then output like this.
So,that didn't work for me.
here, my server.js code
require('babel-register')({presets: ['react']});
var express = require('express');
const fs = require('fs');
var app = express();
app.use(express.static('app'));
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var Home = require('./app/components/index.js');
var AboutUs = require('./app/components/about.jsx');
var Gallery = require('./app/components/gallery.jsx');
var NotFound = require('./app/components/not_found.jsx');
app.get('/', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Home));
response.send(html);
});
app.get('/home', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Home));
response.send(html);
});
app.get('/about', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(AboutUs));
response.send(html);
});
app.get('/gallery', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Gallery));
response.send(html);
});
var port =2000; //process.env.PORT;
app.listen(port, function(){
console.log('Listening application at : http://localhost:' + port);
});
Please, help me.

Multiple var is node app.js

Is it bad form to have multiple var calls, such as:
var init = require('./config/init')(),
config = require('./config/config'),
express = require('express'),
errorHandler = require('errorhandler'),
bodyParser = require('body-parser'),
expressValidator = require('express-validator'),
mongoose = require('mongoose'),
path = require('path'),
_ = require('lodash'),
passport = require('passport'),
passport_config = require('./config/passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
swagger = require("swagger-node-express"),
secrets = require('./config/secrets'),
multer = require('multer');
Or should I set each one by itself?
Since you're using it to import npm modules on a global scope, it's fine. But in general, it's better practice to declare var for each variable. The reason being that missing a , will create any following variables in a global scope. For example, try catching the error in this:
var init = require('./config/init')(),
config = require('./config/config'),
express = require('express'),
errorHandler = require('errorhandler'),
bodyParser = require('body-parser')
expressValidator = require('express-validator'),
mongoose = require('mongoose'),
path = require('path'),
_ = require('lodash'),
passport = require('passport'),
passport_config = require('./config/passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
swagger = require("swagger-node-express"),
secrets = require('./config/secrets'),
multer = require('multer');

express js route is not working, getting a 404 for some reason

I have a link that is suppose to go to a page but every time I click on the link the address changes to the right page but I get a 404 Not Found error.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require("fs");
var routes = require('./routes/index');
var login = require('./routes/login');
var rtc = require('./routes/rtc');
var adminEstimating = require('./routes/adminEstimating');
var adminEWJ = require('./routes/adminEWJ');
var adminTrusses = require('./routes/adminTrusses');
var admin = require('./routes/admin');
var adminMillwork = require('./routes/adminMillwork');
var adminInsulation = require('./routes/adminInsulation');
var adminDrywall = require('./routes/adminDrywall');
var submitted = require('./routes/submitted');
var adminLink = require('./routes/adminLink');
var notAdmin = require('./routes/notAdmin');
var error = require('./routes/error');
var dogReport = require('./routes/dogReport');
var fleetReport = require('./routes/fleetReport');
var fleetLogin = require('./routes/fleetLogin');
var fleetNotAdmin = require('./routes/fleetNotAdmin');
var fleetAdminLink = require('./routes/fleetAdminLink');
var fleetAdminNew = require('./routes/fleetAdminNew');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/leadtime/', routes);
app.use('/leadtime/', function(req, res, next){
var fileName = './public/components/visitorTracker.json';
var fileContent = fs.readFileSync(fileName);
var content = JSON.parse(fileContent);
content.visitorCount++;
fs.writeFileSync(fileName, JSON.stringify(content));
next();
});
app.use('/leadtime/login', login);
app.use('/leadtime/rtcProduction', rtc);
app.use('/leadtime/adminEstimating', adminEstimating);
app.use('/leadtime/adminEWJ', adminEWJ);
app.use('/leadtime/adminTrusses', adminTrusses);
app.use('/leadtime/admin', admin);
app.use('/leadtime/adminMillwork', adminMillwork);
app.use('/leadtime/adminInsulation', adminInsulation);
app.use('/leadtime/adminDrywall', adminDrywall);
app.use('/leadtime/submitted', submitted);
app.use('/leadtime/adminLink', adminLink);
app.use('/leadtime/notAdmin', notAdmin);
app.use('/leadtime/error', error);
app.use('/dogReport', dogReport);
app.use('/fleetReport', fleetReport);
app.use('/fleetReport/fleetLogin', fleetLogin);
app.use('/fleetReport/fleetNotAdmin', fleetNotAdmin);
app.use('/fleetReport/fleetAdminLink', fleetAdminLink);
app.use('/fleetReport/fleetAdminNew', fleetAdminNew);
The route that isn't working is var fleetAdminNew = require('./routes/fleetAdminNew');
I've done the same thing for all my other routes and have had no problems. I've looked for spelling mistakes and I haven't found any.
fleetAdminNew.jade
extends layout
block content
div(class='container')
header
h1 National Lumber Co. / Reliable Truss & Component
h2 Fleet Maintenance Administration
div(class='section')
h3 New Truck
form(method='POST')
label(for='yard') Yard
input(type='text' id='yard')
label(for='vehicle#') Vehicle #
input(type='text' id='vehicle#')
label(for='vehicleDescription') Vehicle Description
input(type='text' id='vehicleDescription')
fleetAdminNew.js (not finished yet, still need to put post code in)
var express = require('express');
var fs = require("fs");
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('fleetAdminNew', { title: 'Add New Truck' });
});
module.exports = router;
If you have a folder 'routes/fleetAdminNew' then it's pulling the nothing from that instead.

Categories