Render an html in Node with js

Asked

Viewed 1,426 times

0

I can route in the Node where it calls an html page, but the html page has a file. js and when it is called the error of not finding the JS file.

Can someone help me?

Structure:

main folder : project

subdirectories: config, js, views

within config:config.js within js: request.js within views: index.html

config.js:

var express = require('express');
var port = 3000;
var app = express();
var bodyParser = require('body-parser');


app.use(bodyParser.urlencoded({extend : true}));
app.use(bodyParser.json());
app.listen(port);


app.set('views', './views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/views/'));

module.exports.express = function(){
    return app;
}

app.js(is located in the main folder):

var app = require('./config/config.js').express();
app.get('/',function(req,res){

  res.render('index.html');
});
  • Post your Node, html and folder structure

  • See if it helps, I edited

  • That one arquivo.js is a file to run on the server or to be called from HTML and run in the browser?

2 answers

1

Place config.js in the root folder, so it is easier to keep the project, and the application files in the folder app(can choose any name), index.html can be isolated as it is also easier to maintain, other templates can be allocated in the folder views

config.js

app

index.html

js > request.js

views > othersTelas.html

And find the index with the express

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/app'));

0

To use javascript code inside nodejs with express is simple:

app.use(express.static(path.join(__dirname, 'nome_da_pasta_com_seus_arquivos_js')))

Then just reference in your html file the js file you want and restart the server.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.