App.js to redirect to a module - node.js

I am debugging into a NODE JS application and I am very new to node js. I have a REST module file
students.js
module.exports = function (service) {
/**
* Retrives data from DB
*/
service.get('/mobile/students', function (req, res) {
res.set('Content-Type', 'application/json')
.status(200)
.json(DBHelper.getAllStudents());
});
service.post('/mobile/students', function (req, res) {
res.status(200).json(data);
});
});
To run it locally I am using the following app.js
const express = require('express');
const app = express();
var routes = require('./students');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3010, function () {
console.log('Example app listening on port 3010!')
});
When I hit
http://localhost:3010/students, I am hitting a 404.
How do I explicit route the path to the student modules?

you need to add routes(app); line after var routes = require('./students'); then Your routes will be mounted..
http://localhost:3010/students if use this it will prompt you again with 404 but if you use http://localhost:3010/mobile/students it will produce desire output..

Related

Expressjs server and external api calls

I'm new to frontend development and express server. When I tried to start an express.js server with react (with axios calls to external apis), it seems express.js is adding 'localhost:3000' in front of the external API calls so they fail.
In my server.js:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '.', 'dist');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server is up!');
});
Which leads to the API call to www.example.com/api/ to become http://localhost:3000/www.example.com/api/
I also tried to filter the req by writing:
app.get('*', (req, res) => {
if (req.url.match(/\/api\//) === null) {
res.sendFile(path.join(publicPath, 'index.html'));
}
});
But it does not change things...
Can anyone help out this newbie that is me?
Update1 Adding the code for calling the api:
This is the api call:
const getSomething = () => {
try {
const url = endpoints.GET_SOMETHING;
return axios.get(url);
} catch (err) {
console.log(err);
}
};
endpoints.GET_SOMETHING is the api URL: www.example.com/api/getSomething
You need to put a / in the url
app.get('/*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
and also your endpoint url should start with https://, http:// or //

I'm new with API's. I'm working with rest API's in node js. I'm not getting how to go from one route to another?

In the example below, if I'm in localhost:5000/A and i want to go to localhost:5000/B, but from within localhost:5000/A, how can i do that via a button ?
var express = require('express');
var app = express();
// Our first route
app.get('/', function (req, res) {
res.send('Hello Index!');
});
// Our A route
app.get('/A', function (req, res) {
res.send('Hello A!');
});
// Our B route
app.get('/B', function (req, res) {
res.send('Hello B!');
});
// Listen to port 5000
app.listen(5000, function () {
console.log('Dev app listening on port 5000!');
});
Just try this :
app.get('/A', function (req, res) {
res.send('Hello A! <button>Click me</button>');
});
Or you could serve an HTML page containing this code.
Hope this answers your question. If not please reach back to me.

Can get('/', function (req, res){} can't be called server

I was working on fetching data from mysql and using it to create d3js graph on node.js. I learnt that server can only be made from modules 'http' and 'request'. If I am not using them and using
app.get('/', function (req, res) {
res.render('index', {
//
});
});
app.listen(port, function () {
console.log('running server on port ' + port)
});
They are solving the same purpose.
What concept of server am I missing? What are the limitations of fetching data this way?
use express web framework :
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
let port=3000;
app.listen(port, function () {
console.log('running server on port ' + port)
});

Why Express.js' app.get() can only work in the same file app.listen() is called?

When app.listen() is in the same file as app.get(), it works; and when I add app.get() calls in other files via require, they don't work:
// ~ means root folder
// This below is in ~/index.js
var routes = require('~/routes/routes.js');
var server = app.listen(3000, function () {
console.log('Listening on port %d', server.address().port);
});
app.get('/snails', function (req, res) {
res.send('ESCARGOT');
});
// This below is in ~/routes/routes.js
var app = module.exports = require('exports')();
app.get('/birds', function () {
res.send('PENGUIN');
});
// SUCCESS -> localhost:3000/snails will return "ESCARGOT"
// FAIL -> localhost:3000/birds will return "Cannot GET /birds"
Second example to prove the point; this time, app.listen() is moved to routes.js:
// ~ means root folder
// The below is in ~/index.js
var routes = require('~/routes/routes.js');
app.get('/snails', function (req, res) {
res.send('ESCARGOT');
});
// The below is in ~/routes/routes.js
var app = module.exports = require('exports')();
app.get('/birds', function () {
res.send('PENGUIN');
});
var server = app.listen(3000, function () {
console.log('Listening on port %d', server.address().port);
});
// FAIL -> localhost:3000/snails will return "Cannot GET /snails"
// SUCCESS -> localhost:3000/birds will return "PENGUIN"
Why is this so? Is it because app.listen() only targets the file that it is called in?
You need to export your app and include it in your routes file
module.exports = app;
And then in your routes file
var app = include('pathtoyourapp.js');
Then you'll have access to your app in your routes file.
You should be doing something along the lines of this in routes/routes.js
module.exports = function(app) {
app.get('/birds', function(req, res, next) {
res.send('Hello');
});
};
and in the index.js
var app = express();
app.get('/snails', function(req, res, next) {
res.send('SNAILS');
});
require('./routes/routes')(app);
app.listen(3000);
should now work.
BTW i'm not 100% sure what you are trying to do by doing require('exports')(), and it looks weird that you are actually exporting that, instead of the app (that contains the new birds route) in routes/routes.js, so that's why it probably doesn't work. Try the way I suggested.
Let me know if you need any additional things.
Use example:
var express = require('express'),
http = require('http'),
port = Number(process.env.PORT || 3000),
app = express();
app.get('/', function(req, res) {
res.end('Test message');
});
http.createServer(app).listen(port);
Most important is:
http.createServer(app).listen(port);
Send app argument for manipulation of servers behaviors.

using object in another js file

I am getting my hands on node.js and I am trying to understand the whole require/exports thing. I have the following main app.js file:
/app.js
var express = require('express'),
http = require('http'),
redis = require('redis'),
routes = require('./routes'),
var app = express(),
client = redis.createClient();
// some more stuff here...
// and my routes
app.get('/', routes.index);
then, I have the routes file:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
I can of course use the client object on my app.js file, but how can I use the same object in my routes?
Since req and res are already being passed around by Express, you can attach client to one or both in a custom middleware:
app.use(function (req, res, next) {
req.client = res.client = client;
next();
});
Note that order does matter with middleware, so this will need to be before app.use(app.router);.
But, then you can access the client within any route handlers:
exports.index = function(req, res){
req.client.get(..., function (err, ...) {
res.render('index', { title: 'Express' });
});
};
The easiest way is to export a function from your routes file that takes a client, and returns an object with your routes:
exports = module.exports = function (client) {
return {
index: function (req, res) {
// use client here, as needed
res.render('index', { title: 'Express' });
}
};
};
Then from app.js:
var client = redis.createClient(),
routes = require('./routes')(client);

Resources