Problem - I am not able to get any response from postman when hitting localhost:9000. It should give me a user json back which is in my routes file only for time being. Instead it spits out the following.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/main.ce2f0561.js"></script>
</body>
Setup
Using create-react-app with express to connect.
My folder structure is
--src React app lives in this
--server
-- index.js
-- express.js
-- controllers
-- routes
-- rs_notes.js
rs_routes.js
'use strict';
module.exports = function(router){
const notesController = require('../controllers/cs_notes');
router.route('/', function(req, res, next) {
// Comment out this line:
//res.send('respond with a resource');
// And insert something like this instead:
res.json([{
id: 1,
username: "samsepi0l"
}, {
id: 2,
username: "D0loresH4ze"
}]);
});
};
express.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
const router = express.Router();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
require('./routes/rs_notes')(router);
// Always return the main index.html, so react-router render the route in the client
router.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
index.js
'use strict';
const app = require('./express');
const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
Full project link - https://drive.google.com/file/d/0B35OQMkRo3KcSHlkeXdWVjVjc0U/view?usp=sharing
My questions or doubts are
Am I passing the router in a right way. We used to pass app in this
way prior to express 4 ? So not sure if same structure works here.
I am able to load it in browser by hitting localhost:9000 (server is run by node server command as configured) but not in postman.
I was able to fix up this stack by learning the use of Router appropriately and moving some code here and there. But it was still not working for base route i.e when I simply do router.get('/', ...). Gives the same error message. So I rather reversed the approach of connecting node and react. I published my efforts on medium for the same reason as two separate posts.
https://medium.com/#kushalvmahajan/i-am-about-to-tell-you-a-story-on-how-to-a-node-express-app-connected-to-react-c2fb973accf2
Related
total noob question but I cannot find any solutions to this sorry so last resort is to ask here.
I am trying to learn pug. Have created a boilerplate project and unable to render index page. Ive searched and read as much as I can but all I get is 'Error parsing body of the with expression' error. The index.js looks as simple as follows but stopping me in my tracks:
var express = require('express');
var router = express.Router();
// GET home page.
router.get('/', (req, res) => {
res.render('index', { title: 'Express' });
});
module.exports = router;
if anyone can provide a one liner to point me in the right direction to resolve this and keep rolling on my pug and nodejs journey I'd really appreciate it. Pug is appearing very difficult at this stage despite all the raving about it :/
I have checked one of my old projects. You can try something like this:
Install pug:
$ npm install pug --save
Then set up the app:
const express = require('express')
const app = express()
const port = 3000
// you don’t have to specify the engine or load the template engine module in your app;
// Express loads the module internally, as shown below (for the above example).
app.set('view engine', 'pug')
// views, the directory where the template files are located
// This defaults to the views directory in the application root directory.
app.set('views', './views')
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Example pug file:
html
head
title= title
body
h1= message
Using template engines
I'm deploying a project on my hosting, but I've some trouble with the 'entry point' of my app.
I've developed an application under react js (with webpack).
When I setup it, I don't know which file to make the 'Application startup file'?
For the moment, it's a simple 'server.js' that say hello and give me the current version of node.
When I'm on my project in local, I just launch npm start and it works.
Resolved by editing the 'server.js' file like this :
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
});
app.listen(9000);
For some reason my express router is not processing requests correctly. My router module is in the same directory as the app entry point. The app is located in index.js:
const express = require('express')
const app = express()
// loading router
const mainRouter = require('./mainRoutes.js')
// mounting router
app.use('/', mainRouter)
app.listen(3000)
console.log('Express server running on port 3000')
The router module is located in mainRoutes.js:
const path = require('path')
const express = require('express')
const mainRouter = express.Router()
mainRouter.get('/', function (req, res) {
res.send('Hello World, I\'m Node.js')
})
mainRouter.get('/about', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'about.html'))
})
module.exports = mainRouter
When I launch the server locally with live-server and make the following example request in chrome browser:
http://127.0.0.1:8080/about
I get the following error response:
Cannot GET /about
Does anyone have any idea as to what the issue is?
The server is listening on port 3000: app.listen(3000)
But you're trying to access it from port 8080: http://127.0.0.1:8080/about
Try http://127.0.0.1:3000/about
When the user goes to mydomain.com/game, I want the user to see what is displayed in my public folder. This works completely fine when I do this:
app.use('/game', express.static('public'))
The problem is that I want to extract some information from the URL, but as I do not know how to continue the routing when using a static site, I can't extract any information. For example, if the user inputs mydomain.com/game/123, I want to retrieve 123, but still route the person to my public folder, like mydomain.com/game does.
Any ideas on how to handle this problems?
This has worked for me in a similar situation
app.use('/game/:id', (req, res) => {
// do something with id
res.redirect(302, '/game');
}
Try to use two middlewares: first is your static middleware, the secont is the fallback, with id (123)
app.use('/game', express.static('public'));
app.use('/game/:id', function(req, res) { // when static not found, it passed to this middleware, this process it
console.log('your id', req.params.id);
res.send('ok');
});
If you are using react static files and you want to serve all react routes using express then you have to do thing like below-
1.First of all you have to run command in your react folder
npm run build
this will create your build folder in react app having one index.html file which you have to serve through express.
Now come to your server.js file and write there
const express = require('express');
var path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req,res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
Introduction
I have built some back end functionality in Node (First time using Node). Problem is that the whole thing was built in one page (index.js) so now im following a few basic tutorials and setting out express router middleware and now trying to follow a modular MVC approach,
This code is simple but brakes when I separate into two pages Server.js and config.js. I know its a simple problem but i cant spot it. can someone help spot the problem and maybe improve the structure ?
Problem
I go to http://localhost:8080/about or a different route and I get
Cannot GET /about
rather than the correct print out.
back-end/server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Server has started!! ' + port);
back-end/config.js
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
router.get('/', function(req, res) {
res.send('im the home page!');
});
// sample route with a route the way we're used to seeing it
router.get('/sample', function(req, res) {
res.send('this is a sample!');
});
router.get('/about', function(req, res) {
res.send('im the about page!');
});
app.route('/login')
.get(function(req, res) {
res.send('this is the login form');
})
.post(function(req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
app.use('/', router);
As #SLaks said in his comment, you need to import (require) your backend/config.js file. But it's not as simple as that...
In node, variables are scoped to the file in which they appear, so if you simply add require('./config') to your server.js file, that's not going to work either, because the router variable in config.js is local to that file - it's not going to know about the router variable in server.js.
The solution to this is to have the config.js file export a function which the server.js file can use to configure stuff. For example
config.js
module.exports = function(router) {
// set up your router here with router.use, etc.
};
server.js
var configure = require('./config');
// after you set up your express router...
configure(router);
// now start listening