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.
Related
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('proiect'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage.html');
else
res.redirect('login-error.html');
res.end();
});
app.get('/homepage.html',function(req,res){
console.log('aaa');
});
app.get('bios.html',function(req,res){
console.log('aaa');
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage.html');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login.html');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
The server doesnt handle the app.get('homepage.html') or 'bios.html' it just displays the html file in the browser.(should hang and display smth on console).
Am i supposed to serve/render those files instead of directly accessing them in the browser?
Both of those files are in the /proiect/ folder i've included on the server.
Express finds the static HTML file and then returns that to the user. Therefore it skips the route handler you wrote.
If you are trying to perform some server-side logic and returning an HTML page, rather return the page inside your route handler to avoid such side effects. In this case, create your HTML file in a templates folder or something. Then you can put all your static resources in your static folder. So your structure would look something like this:
+ project_folder
+ static
+ css
- style.css
+ js
- app.js
+ templates
- bios.html
- homepage.html
- login.html
- login-error.html
- app.js
Then your app.js would look something like this:
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('static'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.get('/login', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login.html'));
});
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage');
else
res.redirect('login-error');
res.end();
});
app.get('/homepage',function(req,res){
res.sendFile(path.join(__dirname, '/templates/homepage.html'));
});
app.get('bios',function(req,res){
res.sendFile(path.join(__dirname, '/templates/bios.html'));
});
app.get('login-error', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login-error.html'));
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
I am trying to encrypt some text for a HTML project that I am doing and the encryption code I'm using requires a node.js server, but I can't seem to run the function in my original HTML code. I am new to JavaScript and don't really understand a lot of it.
This is the HTML code where I want to call the function with the button:
(the stuff in the button is just some random thing from online and I don't think is relevant)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>test</title>
</head>
<body>
<a href="/Files/TEST.ptf" download="meme14">
TEST.ptf
</a>
<button onclick="
var url = require('url');
var adr = 'http://localhost:3000';
var q = url.parse(adr, true);
console.log(q.host);"
>Encrypt</button>
</body>
</html>
Here is the Node.JS Server's code, I want to call the encrypt function.
// server.js
var express = require('express');
var app = express();
var PORT = 3000;
app.get('/', function(req, res) {
res.status(200).send('Hello world');
});
function encrypt() {
var SimpleCrypto = require("simple-crypto-js").default;
var _secretKey = "-VH5s*#yoj0JDiXQdLyKHwYvttDeoxcarpgaBm9uLZH%Vy0Xw_n0DZ3|BgE7pn%1*APiRV1L*7OlRLIuL&yqIqKw#QLPJc+r+N^dH-Wb3#Zx2TKkvtbobzFW6?Fr$^XObG4K$m$clU3m+1BVx#3O_v6sikvNWwxhVV*q4vrvr7|8qT4*JK3g!*SF-ffDE=?lU$4HuVpiYHTAmW#DNDWeJH*#orX_GY##|=8ip8rskE0TPl-4OC+KCa2re+ND3pwp";
var simpleCrypto1 = new SimpleCrypto(_secretKey);
var plainText = "Hello World!";
var cipherText = simpleCrypto1.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text : " + plainText);
console.log("Cipher Text : " + cipherText);
}
var router = express.Router();
app.use('/*', router);
router.get('/call-java-app', function (req, res, next){
encrypt();
res.send(cipherText);
});
encrypt();
app.listen(PORT, function() {
console.log('Server is running on PORT:',PORT);
});
In your NodeJS code you have to create a Route that call this function and send to client the response; technically.
I hope this code can help you:
var express = require('express');
var app = express();
var PORT = 3000;
var SimpleCrypto = require("simple-crypto-js").default;
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.get('/', function (req, res) {
res.status(200).send('Hello world');
});
app.get('/encrypt', function (req, res) {
res.send(encrypt())
});
app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
});
function encrypt() {
var _secretKey = "-VH5s*#yoj0JDiXQdLyKHwYvttDeoxcarpgaBm9uLZH%Vy0Xw_n0DZ3|BgE7pn%1*APiRV1L*7OlRLIuL&yqIqKw#QLPJc+r+N^dH-Wb3#Zx2TKkvtbobzFW6?Fr$^XObG4K$m$clU3m+1BVx#3O_v6sikvNWwxhVV*q4vrvr7|8qT4*JK3g!*SF-ffDE=?lU$4HuVpiYHTAmW#DNDWeJH*#orX_GY##|=8ip8rskE0TPl-4OC+KCa2re+ND3pwp";
var simpleCrypto1 = new SimpleCrypto(_secretKey);
var plainText = "Hello World!";
var cipherText = simpleCrypto1.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text : " + plainText);
console.log("Cipher Text : " + cipherText);
}
you have to use Ajax to send a request to server and get the response and show to the user, make an Ajax request can help you.
I have a JS file in a folder called public, which also has my CSS file in it. I'm trying to access a function from the JS file (scripts.js), but am having no luck. I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js'. If anyone can help me out, that would be great.
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get('/', function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
var temperature = scripts.converter(data.currently.temperature)
res.render("results", {data: data, temperature: temperature})
} else {
console.log(response.body);
}
});
});
app.get('/results', function(req, res){
res.render("results");
});
app.listen(3000, function(){
console.log("Server has started");
})
scripts.js
module.converter = function(cel) {
var cel = (far - 32) * (5/9);
return cel;
}
exports.data = module;
The path to your module is wrong.
Try var scripts = require("./public/scripts.js"); instead.
You are loading /scripts.js, which is a scripts.js file located at your computers root. To load a file in the current directory, you would do ./scripts.js. In a directory above the current one, it would be ../scripts.js.
If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. directoryname being public in your case
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;
I have a node.js/socket.io project. I'm using Bootstrap in my pages and I display images dynamically on my pages. The problem is that I can't use the images and the Bootstrap files. Node.js/socket.io doesn't recognize the links... I have solved the Bootstrap problem by uploading all Bootstrap files on a distant server and it works! But I can't use local files like my images.
How can I "load" an image folder which I can use the images from it?
Here is my server.js :
var http = require('http').createServer(createServer);
var fs = require('fs');
var url = require('url');
var nStatic = require('node-static');
var express = require('express');
var app = express();
function createServer(req, res) {
var path = url.parse(req.url).pathname;
var fsCallback = function(error, data) {
if(error) throw error;
res.writeHead(200);
res.write(data);
res.end();
}
switch(path) {
case '/galerie.php':
doc = fs.readFile(__dirname + '/galerie.php', fsCallback);
break;
default:
doc = fs.readFile(__dirname + '/index.php', fsCallback);
break;
}
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
http.listen(8080);
This works :
<script src="http://website.ch/LivreOr/js/download.js"></script>
But this doesn't work :
<img src="../LivreOr/img/img.png">
I have solved my problem. Here is what I have changed :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/galerie', function(req, res) {
res.sendFile(__dirname + '/galerie.html');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
//var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
server.listen(8080);