This is a Node project, I'm getting a 'Cannot GET/' error when I try top open up localhost on port 8081. I'm almost certain it's just not reading in the HTML file correctly but I'm not sure.
var express = require('express');
var jsonfile = require('jsonfile');
var bodyParser = require('body-parser');
var app = express();
var file = 'C:/xampp/htdocs/codedb.json';
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('codeStore'));
app.use(bodyParser.json());
app.get('/backEndVersion.html', function (req, res) {
res.sendFile( __dirname + "/" + "backEndVersion.html" );
})
app.get('/somepath',function(req,res){
res.render('backEndVersion.html')
})
When u request somepath u will be rendered the backEndVersion.html file
I suggest u better use ejs or hbs engine for html renderering in nodejs
ejs link
I think you forgot to let the server listen to request. At the end of your file, add :
app.listen(8081)
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 got a problem when working with Node.js and Express.
I try to send an ID (basically a random string) from the client side via jQuery to the server. But no matter what I try... it returns a 404 not found.
My client side javascript:
$.get('/controller/setclickedplace/' + place.id, function(popupHtml) {
$('#popup').html(popupHtml);
});
My server side app.js:
var express = require('express');
...
var app = express();
...
var controller = require('./routes/controller');
...
app.use('/controller', controller);
My server side routes/controller.js (router):
var express = require('express');
var router = express.Router();
//require controller modules
var googlePlacesController = require('../controller/GooglePlacesController');
//Set clicked places ID
router.get('/setclickedplace/:place_id', googlePlacesController.setClickedPlace);
module.exports = router;
My server side controller/GooglePlacesController.js (controller):
exports.setClickedPlace = function (req, res, next) {
var googlePlaceID = res.params.place_id;
res.render('popup', {place_id: googlePlaceID});
};
I have no idea what's wrong there.
Client console says:
GET http://localhost:3000/controller/setclickedplace/9ac35ce7115b1b4d9f5c3a28c0a2d0774cf36d9d 404 (Not Found)
Server console says:
GET /controller/setclickedplace/9ac35ce7115b1b4d9f5c3a28c0a2d0774cf36d9d 404 0.828 ms - 212
Thanks for your answers.
Greetings
Julian
I am trying to find a way to create a new page dynamically on Node.JS with Express when a user submits a form. Here is my idea, but it doesn't work:
var app = require('express')();
var server= require('http').createServer(app);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
function Page(name){ //Create a page prototype
//Some variables and methods specific to the page
app.get('/'+name, function (req, res) {
res.render('index.ejs', {someVars: someVars});
});
}
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
var newPage = new Page(nom);
res.redirect('http://myDomain/' + nom);
});
What is the best way to do it?
You could save names of created pages in database and set optional parameter in express:
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
/* save nom to database */
res.redirect('http://myDomain/' + nom);
});
app.get('/:nom', function(req, res){
/* if nom exists in database -> return ejs template with vars */
/* else return 404 */
});
You should store it in database to prevent having pages that doesn't exist.
You need to add ejs as view engine and make sure you have created index.ejs and then add a get route for dynamic page as following
var app = require('express')();
var server= require('http').createServer(app);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// set the view engine to ejs
app.set('view engine', 'ejs');
app.get("/:pageName", function (req, res) {
var pageName = req.params.pageName;
res.render('index.ejs', {someVars: someVars});
});
//When a user submits a form, create a new page
app.post('/submit', urlencodedParser, function(req, res){
var nom = req.body.nom;
res.redirect('http://myDomain/' + nom);
});
I hope this will help you
I wanted to send code to some node application and I use the postman with post message and in the body I put the following:
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
return app;
}
in the header of the request I put
content-Type application/text/enriched
in the node code I use the following
module.exports = function (app) {
fs = require('fs');
var bodyParser = require('body-parser');
...
app.post('/bb',function(req,res){
var fileContent = req.body
and the file content is empty ,I was able to see that it works since it stops in debug
If you want to add a custom content type then you need to keep two things in mind:
Content type couldn't be "application/text/enriched", in other hand "application/text-enriched" is ok. Max two "words".
You must provide a custom accept header on body parser configuration BUT body parser return you a buffer when you use custom header
See the example:
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.raw({ type: 'application/text-enriched' }))
app.post('/demo', function(req, res) {
console.log('POST DATA')
console.log('STREAM', req.body)
console.log('STREAM to STRING', req.body.toString())
res.status(200).send('ok');
});
app.listen(3000);
You can test in your console with curl:
curl 'http://localhost:3000/demo' -d 'name=john&surname=doe' -H 'Content-Type: application/text-enriched'
I recommend you try to not use a custom content type header because things are easier. I hope that my explanation help you.
I'm working on a project, which will use given coordinates from a txt file and graph them.
My problem right now: I'm trying to use ejs to render the coordinates into my html file, but it just isn't working right. Ejs always just renders: undefined.
Here is the code:
var http = require('http'),
fs = require('fs'),
express = require('express'),
app = express();
app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
//Readerfunction
function readLines(input, done) {
//.....
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
obj[key1] = [];
obj[key2] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
});
console.log('X:', obj[key1]); // all the variables are logged correctly.
console.log('Y:', obj[key2]);
app.get('/', function(req, res) {
res.render('graph.html', {cordinates: obj});
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
In the html file:
<%= cordinates.obj %>
I hope you can help me, solve this problem! :-)
Greetings,
JS
Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.