failed to load static files express js - javascript

new to node development.
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
my content gets as below
server.listen(1337);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
I am trying to get static file as below
server.use("/", app.static(__dirname + '/'));
but it doesnt wonk getting errors.
How to get staTIC files?

just read express docs
var express = require('express'),
app= express(),
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
app.use("/", express.static(__dirname + '/'));

the static function is a method on the express module.
So it should be:
var express = require('express'),
app = express(),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/'));

Related

Express js router not working

This is my home.js code
// import modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require ('cors');
var path = require ('path');
var app = express();
const route= require('./routes/route');
//port no
const port =3000
app.use(cors());
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
app.use('./api', route);
//testing server
app.get('/', (req,res)=>{
res.send('foober');
})
app.listen(port,()=>{
console.log('server started at port:' + port);
});
And this the route.js code
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res, next )=>{
res.send('retrieve contact');
});
module.exports =router;
But whenever I run 'localhost:3000/api/contacts' i get 'Cannot GET /api/contacts' error. I am very new at this, what am I doing wrong?
A dot in an url is there to seperate domains, if your route is mounted at ./api you would have to visit yourserver.com./api which won't work as the url is invalid.

Node.js: "require not defined" error happens in only one js

I have multiple node.js files in a project.
The server code is below:
app.js
var express = require('express');
app.use(express.static(__dirname + '/node_modules'));
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/routes", express.static(__dirname + '/routes'));
var aws_router = require('./routes/aws')(app);
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
server.listen(8080);
Now I have another file aws.js in ./routes which essentially contains database operations
aws.js
var express = require('express');
var AWS = require('aws-sdk');
var credentials = new AWS.SharedIniFileCredentials({profile: 'default'});
AWS.config.credentials = credentials;
/*more code here*/
Now I am getting error
"Uncaught ReferenceError: require is not defined" in aws.js file for var express = require('express'); Why is that? The same definition is there also in app.js where it is all good.
What am I missing?

react app with express.js route setup

I was using angular.js and I do this in express.js
app.get("*", function (req, res) {
res.redirect('/#' + req.originalUrl)
})
so that the browser will use the route of angular instead of express. But how to do that with react router? I have 2 folder, named server and client, server folder has express and api logic while client folder simply a react app.
You need to put the path in of the HTML file you are rendering your app to
app.get("/",(res,res) => {
res.sendFile('put the path of the html file you are rendering your app into here');
}
here is an example of a express server.js that works with react
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
var PORT = process.env.PORT || 3000;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
app.use(express.static('./public'));
app.get('/', function(req,res){
res.sendFile('./public/index.html');
});
app.listen(PORT, function(){
console.log("Listening on port: " + PORT);
});

Node + Express JS API is not working

I'm a beginner in node.js but I try a little harder to setup a structure in node + express js.I start doing with the front-end and separate API structure.I put a single app.js for both API and front-end.But my API is not working. it gives error Cannot GET /api/users when i call http://localhost:3000/api/users. please help
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(controller)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
In your routes.js file you are exporting two things. Try to only export the router
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
router.get('/users', usersController.getUser);
module.exports = router;

Static Content Serving Not Working In Express

var express = require('express');
var app = express();
app.get('/', function(req, res){
app.use(express.static('../../www'))
})
app.listen(8080)
according to docs this should work but it just returns a page of garbled text
It's better to use path module to join the current folder and relative path to an absolute path.
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, '../../www')));
app.get('/', function(req, res){
res.send('done');
});
app.listen(8080);
As #bulkan comments, you use /style.css to access www/style.css.
Move the app.use(express.static('../../www')); outside of the app.get like so;
var express = require('express');
var app = express();
app.use(express.static('../../www'));
app.get('/', function(req, res){
res.send('done');
});
app.listen(8080);
http://expressjs.com/api.html#app.use

Categories