I'm new in Angularjs and i'm trying to create a basic one page app using ngRoute. But i have a problem. I wan't my user to get the index.html file everytime. But if the url is /page1 my server is returning the page1 so index.html isn't loading. I tryed to fix it by doing like that :
Angular file :
test.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : '/page1',
controller : 'trapController'
})
.when('/test', {
templateUrl : '/page2',
controller : 'trapController'
});
$locationProvider.html5Mode(true);
});
Node.js file :
require('dotenv').load();
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const bodyParser = require('body-parser');
const path = require('path');
const apirouter = require('./apirouter');
const viewrouter = require('./viewrouter');
app.use('/api', apirouter);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.engine('html', require('ejs').renderFile);
app.use('/*', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
// START THE SERVER
// =============================================================================
app.listen(port, () => {
console.log('Server running on port ' + port);
});
But this way nothing is working.. It seems like every call is asking to the server and not looking into the public folder. So when i call for a .js file it load me a new index.html file... I don't know how to do.. Can you help me ? :)
I was apparently doing wrong with :
Better use this :
app.use('/', express.static(__dirname + '/public'));
Than this :
app.use(express.static(path.join(__dirname, 'public')));
Related
I am building a Node.JS app with Express and Handlebars to serve the public content. The app is running in pm2.
The app is working fine, but I want to serve static files. I added 2 static routes which are loaded fine when I check the Express log.
But when I try to access the files, I get a 404. I noticed the message on the 404 states "Cannot GET /js" where I would expect "Cannot GET /scripts/scripts.min.js".
The URL should be on /scripts/scripts.min.js, internally it's located inside a public folder:
app.js
public
scripts
scripts.min.js
images
styles
Here is my app.js:
const express = require('express');
const { engine } = require('express-handlebars');
require('dotenv').config();
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const {
NODE_ENV,
PORT,
HOST,
} = process.env;
// Use body-parser middleware
app.use(bodyParser.json());
// Use express-handlebars as the view engine
app.engine('handlebars', engine({
defaultLayout: 'main',
layoutsDir: __dirname + '/views/layouts',
partialsDir: __dirname + '/views/partials',
}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')))
app.use('/scripts/monaco/', express.static(path.join(__dirname, 'node_modules','monaco-editor','min','vs')));
// Define routes
app.get('/', (req, res) => {
res.render('home', { title: 'Home' });
});
app.get('/debug', (req, res) => {
res.send(__dirname + '/public')
})
app.post('/', (req, res) => {
console.log(req.body);
res.send('Success');
});
// Load external routes (also tried the staticFiles by using res.sendFile)
require('./routes/processing')(app);
// require('./routes/staticFiles')(app);
// Start the server
app.listen(PORT, () => {
app.currentServer = {
host: HOST ? HOST : "127.0.0.1",
port: PORT,
};
console.log(`Server init on: http://:${PORT}`);
});
I tried serving the files using express.static, I also tried sending them trough specific routes by using res.sendFile.
It looks like Express (or something else) is interpreting the URL path incorrectly. /scripts/scripts.min.js is downgraded to /js so it seems.
I hope anybody has a clue!
I've made this sample code, but first let me show you my folder struture.
---public
-----css
------style.css
---views
-----video.hbs
-----video2.hbs
---server.js
this is my server code.
const express = require('express');
const app = express();
const hbs = require('hbs');
const port = process.env.PORT || 8080;
app.use(express.static(__dirname + '/public'))
//Express hbs engine
hbs.registerPartials(__dirname + '/views/parciales');
app.set('view engine', 'hbs');
app.get('/video', (req, res) => {
res.render('video.hbs');
});
app.get('/video/2', (req, res) => {
res.render('video2.hbs');
});
app.listen(port, () => {})
Now the problem is the next... When I got to localhost:8080/video my css is working fine but when I goin to /video/2 my css it's not showing up, any solution?
You're probably importing your CSS as ./css/style.css. You need to import it as /css/style.css.
I have a server running on Node Js. What I'm doing is whenever the users submit something to save their input to a text file. When I run my server as a localhost it works and saves the input to the file. Whenever I run it on the real published server it doesn't. Is there a way to accomplish it on the real server without a database?
My code:
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8081;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendFile('main.html');
});
app.listen(port, function(){
console.log('Server is running on port:' + port);
});
app.post('/submit', function(req, res){
var data = fs.writeFileSync('fileSync', req.body.rank, 'utf8');
return res.sendFile('success.html');
});
Thank you in advance!
I'm learning MEAN stack with 'Getting MEAN with...' book, and problem is older Express version in books than i use.
The first step is to tell our application that we’re adding more routes to look out for,
and when it should use them. We already have a line in app.js to require the server
application routes, which we can simply duplicate and set the path to the API routes
as follows:
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
Next we need to tell the application when to use the routes. We currently have the following line in app.js telling the application to check the server application routes for
all incoming requests:
app.use('/', routes);
Notice the '/' as the first parameter. This enables us to specify a subset of URL s for
which the routes will apply. For example, we’ll define all of our API routes starting
with /api/ . By adding the line shown in the following code snippet we can tell the application to use the API routes only when the route starts with /api :
app.use('/', routes);
app.use('/api', routesApi);
And there's listing of my app.js file:
var express = require('express')
, others = require('./app_server/routes/others')
, locations = require('./app_server/routes/locations')
, routesApi = require('/app_api/routes/index')
, ;
require('./app_server/models/db')
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/app_server/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
Can someone explain me how to do the same in my Express version ?
In Express 4, this is done using Router Middleware. More info is available on Express Routing here.
A Router is simply a mini express app that you can define middleware and routes on that should all be packaged together, ie /api should all use apiRouter. Here is what apiRouter could look like
apiRouter.js
var express = require('express')
var router = express.Router(); // Create our Router Middleware
// GET / route
router.get('/', function(req, res) {
return res.status(200).send('GET /api received!');
});
// export our router middleware
module.exports = router;
Your main Express app would stay the same, so you would add your router using a require() to import the actual file, and then inject the router with use()
Express Server File
var express = require('express');
var app = express();
var apiRouter = require('../apiRouter');
var port = process.env.PORT || 3000;
app.use('/', apiRouter);
app.listen(port, function() {
console.log('listening on ' + port);
});
I got a very similar problem with this post Learning Node - Express Public folder not working
I added to my server.js
app.use("public",express.static(__dirname + '/public'));
But when I do
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css
Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.
Here is my server.js
var express = require('express')
, cors = require('cors')
, app = express()
, mongoose = require('mongoose')
, models = require('./models')
, bodyParser = require('body-parser')
, controllers = require('./controllers')
, port = 8081//process.env.PORT || 3000
// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
if (err) throw err;
console.log("mongoose connected")
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("RESTful Web Services listening at http://%s:%s", host, port)
})
})
Here is the index.js in the controller folder
var express = require('express')
, router = express.Router()
, users = require('./api/users.js')
router.use('/api/user', users);
router.get('/', function (req, res) {
res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));
router.get('/views/demo', function (req, res) {
res.sendFile('/views/demo.html')
})
module.exports = router
Actually, if I run
http://localhost:8081/views/demo.hmtl
I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"
What did I miss?
I added the following to the server.js and it worked.
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));