nodeJs display on web browser - html

Just want to display my node.js result on web browser..
is it possible?...
here's my code:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
when I try to run that code on cmd it works. The code gets all the .txt file on a specific directory.
here's the result:
then when i tried to load it on my browser the result goes like this
Im also planing to add all the result filename to database mysql once the node.js code fixed.. is that also possible?..
thank you.. this is my first time to create a node.js

Use the express router to accept GET request from your browser :
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});

Nicolas is right, express can achieve this. Just remember to install it using NPM, this can be done by executing following command under the directory where package.json is:
npm install --save express
however, you would also need to write into response of the server so it shows on website. So for example, using Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});

Related

.JS Not running on VS Code

const express = require("express");
const app = express();
app.get("/hello", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
I run this simple code in VS code but It isn't showing in localhost 8080 on web browser
I want to know what did happen and How to solve this one ?

express.json vs bodyParser.json

I'm writing a relatively new app and was wondering which I should use:
express.json()
or
bodyParser.json()
Can I assume they do the same thing.
I would like to just use express.json() as it is built in already.
Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.
bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.
The release history for 4.16.0 is here for those who are interested, and the pull request is here.
YES! Correct
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Yes both are same .
if you go into the file node_module/express/lib/express.js
you can see under module dependencies body parser module is already imported
/**
* Module dependencies.
*/
var bodyParser = require('body-parser')
//other modules
the objects and methods inside bodyparser module are accessible as they are exported using the special object module.exports
exports = module.exports = createApplication;
exports.json = bodyParser.json
this is accessible from express object just by calling
express.json()
Yes!! you can use both of them. However, since express.json() is now already built into express, it is wiser to use express.json() than the bodyParser.json().
Yes!! Due to the widespread opinion of the people to integrate body-parser back with the express, the latest release does exactly this. You should be right to assume that both perform the same tasks, that is to recognize incoming request object as JSON objects. Feel free to use either.

valid json format gives error “<“ while parsing also view engine error 500 using mean stack angular 2+

Mean server with angular 2+.
I have a dataservice.js that requests a get to the server, to receive a json response from the http://localhost:3000/server/routes/api/test.js
This gives me an error 500 view engine not selected,
My understanding is angular doesn’t require a view engine? As the angular/ browser takes care of that.
Somehow the routing doesn’t seem to work when I do a getter to the api.
The angular routes work with the html components, but via the dataservice a get request to the mongodb doesn’t work either. The get/test most often returns error 500 no view engine selected as well.
If it does return something, it returns an error message “<“ not in jsn format.
How do I make sure that the routing works for my get and post messages and they are returned back in json format and not in HTML.
And how do I figure out that it uses the correct routing? I somehow doubt that the rouitng for the get/ post messages seem to use express rather then the angular modules
I am quite new to stack overflow/ Mean server so if you require more info please let me know.
FYI
I have been able to get a json file from the server (not the database) via a get. This worked. So why is it that a get to the database doesn’t seem to work and the same question about why I can’t seem to get a json response from the http://localhost:3000/server/routes/test/api.js in the api.
I spent a full 2 days troubleshooting to no result.
in my api.js
router.get ('/test', function (req, res, next) {
res.json({'testMessage': 'everything is going ', 'someNumber': 457});
});
In the server.js
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require ('morgan');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var chat = require('./server/routes/chat');
var app = express();
var passport = require ('passport');
var cookieParser = require ('cookie-parser');
var session = require ('express-session');
var config = require ('./config/database');
var engines = require('consolidate');
var mongoose = require('mongoose');
var router = express.Router();
// this is where I set up the routing for the api
// in the root of the project I created server directory and
// within it a routes directory that holds the api.js
var api = require('./server/routes/api');
mongoose.Promise = require ('q').Promise;
require('./config/passport')(passport);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(morgan('dev'));
app.use(session({
secret: 'secret123',
resave: true,
saveUnitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//this is where I set up the routing is something wrong here?
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use('api', api);
thx everyone, I moved
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
below
app.use('api', api);
and changed it to:
app.use('/api', api);
Problem solved, if app.get('*') is read first it will send all requests to index.html instead. So make sure any other routings go above it.

NodeJs cat server empty JSON output issue

I a beginner following a nodejs tutorial.
From said tutorial, I generated the following code:
[Index.js]
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var cats = require('./cats.js')(app);
var server = app.listen(3000, function(){
console.log('Server running at http://127.0.0.1/3000');
});
[Cat.js]
var _ = require('lodash');
module.exports = function(app){
_cats = [];
/*
Create
*/
app.post('/cat', function(req, res){
console.log('Testing: ' + req.body);
res.json({info: 'Cat created successfully!'});
});
/*
Read
*/
app.get('/cat', function(req, res){
res.send(_cats);
});
.
.
.
.
When I start the node script, and post some json cat data as described in the tutorial, my web browser displays empty json brackets for each json input I made.
Can anyone tell me what I missed or I'm doing wrong? Why do I get empty JSON brackets instead of my cat data printed out?
I'm an utter newbie at NodeJS so I apologise if I have not described issues adequately.
UPDATE:
I'm using the Postman Chrome extension to POST json, {'name':'sam','age':'1','type':'alley'} to http://localhost:3000/cat.
The tutorial I'm following is on PluralSight. I don't think it's accessible without an account but they do offer a couple of days free to get you started.
Take a look at this working sample:
var express = require('express');
var app = express();
var cats = [];
var counter = 1;
app.post('/cat', function (req, res) {
cats.push({id: counter, name: 'Jacklyn'});
counter++;
res.json({info:'cat created successfully'});
});
app.get('/cat', function(req, res) {
res.json(cats);
});
app.listen(8888);
You need to send at least one POST request in order to have a cat in the array and after each new POST request the amount of cats will increase.
It's because the code you posted does not update the _cats array. The code for post handler should be:
app.post('/cat', function(req, res){
console.log('Testing: ' + req.body);
_cats.push(req.body); // This is the missing line
res.json({info: 'Cat created successfully!'});
});
Here I assume that the body contains a single object and it is already parsed. If not, you can add required manipulations...
Edit
It seems that the request body should be parsed. The express framework has an additional module, the body-parser, which is used for this purpose:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // this will parse json requests
For more information, see bodyParser on GitHub.

Displaying local images in static html served by NodeJS

I have a NodeJS app that renders index.html, but I can't get index.html to find the images in the folder it's located in.
Here are the contents of index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get ('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(80, function(){
console.log('listening on *:80');
});
It serves index.html successfully but all images I supply it are broken links.
The following html does not work
<img src="img/myimage.png">
and my file structure is
myApp - folder
index.js
index.html
img - folder
myimage.png
I've tried several variations such as
<img src="/img/myimage.png">
<img src="./img/myimage.png">
I've also tried placing the image directly in the app folder with index.html and trying
<img src="myimage.png">
But the link to the image is still broken.
const express = require("express");
const app = express();
If you have the images in a folder named "Images" and you want to point to the image in the folder as "img/myimage.png", then use this:
app.use('/img', express.static(__dirname + '/Images'));
This way you can also keep your actual images folder name private.
I was able to resolve the issue by changing
var app = require('express')();
into
var express = require('express');
var app = express();
I then added
app.use(express.static(__dirname + '/img/'));
In the declaration of static file you will use in the express app, you have to put your files (images, songs, file) into public folder. Then, your express and ejs will show your file from the public folder as a root of that file.
var express = require("express");
var app = express();
app.use(express.static('public'));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("main");
});
app.listen(3000, function(req, res){
console.log("Auth server started!");
});
EJS folder is right here.
<h1>Secret Page!</h1>
<img src="anna.jpg"/>
<img src="https://i.imgur.com/NcXbX08.jpg" alt="">
After all, reload your nodejs app.
Do you mean broken links in the browser ? so the browser can not open the links rendered in index.html ?
The browser will probably need full paths to the images .. it doesn't seem that your node server is sending the full paths in the index.html file it passes to the browser.. have a look on that ..