I'm using Express and create-react-app.
My React app is a ways along, and now I'm trying to serve it from an Express server.
// server/app.js
const express = require('express');
const path = require('path');
const app = express();
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
// serve main file
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
(My build directory is populated when I do npm run build.
I view the page in Chrome, and what happens when loading the page at localhost:3000 is the Console prints Uncaught SyntaxError: Unexpected Token <, and in the Sources tab it shows that the content of my CSS and JS files are simply the same as index.html: as in this image.
This seems like a recognizable issue, so hopefully someone has seen this before. I'm sort of stumped on where to even begin, especially because I was actually serving the app from Express successfully at first. Then this started happening, then it stopped after some random switching of git branches and reverting and replaying changes, and then it started happening again. So I'm not even sure what makes it happen or not happen.
It appears that your app.use(express.static... call is failing, so instead all of the requests (including for the static assets) are being handled by the app.get('*', (req, res) => { part.
As you are intending to use this to serve a React app, I'd suggest taking inspiration from a boilerplate, "to see how it's done". I personally use NYTimes's kyt project and there's react-starter-kit too.
Try the following code changes which are detailed from the express documentation - serving static files in express:
Replace
app.use(express.static(path.resolve(__dirname, '..', 'build')));
With
app.use(express.static('build'))
Remove
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
The problem was "homepage": ... in package.json.
When npm run build runs and there is a homepage URL in package.json that has a non-empty path (like a Github Pages URL like this, https://username.github.io/project_name, where "/project_name" is the path), it changes where it expects the files inside /build to be. The requests for my js and css were going to /project_name/static/... instead of /static/....
It even said in the log output of npm run build:
The project was built assuming it is hosted at /project_name/.
You can control this with the homepage field in your package.json.
On my localhost, it wasn't hosted at /project_name/, so the paths were off.
Related
I have a node js and express server I run on localhost. Recently, while changing the server code from
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
to
app.get('/', (req, res) => {
res.send('home');
});
The server still serves the "index.html" file and does not send the message "home". I also tried deleting all my "app.get()" and "app.post()" functions and it still runs as it was before the changes. I have double checked that I saved the file and restarted the server but even then, still does the same thing. The odd thing is that when changing anything else in the server code aside from my express code it runs as expected.
I tried searching my problem but no one is experiencing the same issues. Any help is appreciated, thanks.
All of your code is not listed, so this is an educated guess, but I would check to see if you are using express.static or another package to serve the directory your index.html file is in via app.use() before your routes. By default express.static will serve index.html if presented a root path ('/').
I am using docsifyjs to create a documentation. But I wanted to add Authentication to access the docs.
Basically we serve the docs with following commands
Initializing docsify
docsify init ./docs
After the init is complete, you can see the file list in the ./docs subdirectory.
index.html as the entry file
README.md as the home page
.nojekyll prevents GitHub Pages from ignoring files that begin with an underscore
We can now serve the mark-down files as HTML with following commands.
docsify serve docs
or
cd docs && python -m SimpleHTTPServer 3000
or
npx http-server docs
Here docsify is served by giving the path of initialized directory.
But I am not able to figure out how to serve this with expressJS. So that I can add authentication.
I have tried adding app.js to ./docs and added the following code but markdown files are not being rendered.
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
var app = express();
app.use(serveStatic('/', { 'index': ['index.html', 'index.htm'] }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
})
app.listen(8000);
Please help. Thanks
EDIT ------------
so I figured out the issue, restarting and reloading nginx didn't have any effect, but if I stoped the nginx instance, then restarted it, any changes I made to the server files took effect. It's great that I figured it out, but could anyone give me some insight into why this is? It's better if I understand why this was happening. Any changes I made to the client side files such as the html files took affect immediately, it was only the server files that I had to stop then restart the nginx instance for it to take affect.
ORIGINAL POST BELOW----------------------
Any changes I make to the server side files of my deployed Node.js app with express.js isn't being seen by ubuntu. Basically, I have a mean app deployed on ubunut, it is a multipage page app, with only one of those pages having partials, so i use my routes.js
to catch the routes and send them to my main.js file to tell express and node which html or ejs file to load.
I made changes to the version on my computer so that all other routes would go to a certain html, it works great. But I pushed my changes to github, then pulled them in my ubuntu instance, and it's not working. All other changes I made to the project during this time that were pushed with it have taken affect. But, it's like ubuntu isn't letting node see any changes to the routes.js file, the code is there, I've even altered it with 'vim' from my terminal, but any changes I make, even ones that should break it, aren't seen by node. And going to an unexpected route displays the 'cannot GET...' page.
I've wracked my brain, but i'm stumped, the code is there and I can change it, I've altered html pages via vim to test it. But both, the routes.js file that handles my routing and my server.js file aren't reflecting my changes, even when I change things that should break it. Any ideas? Let me know if you need anymore info, i've included my files below. Also, I use nodemon so that it restarts automatically anytime changes are made
SERVER.JS FILE -------------------------------
var express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, './client')))
app.use(express.static(path.join(__dirname, './client/views')))
app.use(express.static(path.join(__dirname, './bower_components')))
app.set('views', path.join(__dirname, './client'));
app.set('view engine', 'ejs');
require('./server/config/routes.js')(app)
var port = 8000
app.listen(port, function(){
console.log('Server on port: ' + port)
})
ROUTES.JS FILE -----------------------------
var Main = require('../serverControllers/main.js')
module.exports = function(app){
app.get('/', Main.main)
app.get('/contact', Main.contact)
app.get('/algorithms', Main.algorithms)
app.get('/projects', Main.projects)
app.get('*', Main.other)
app.use(Main.other)
}
MAIN.JS FILE ----------------------
module.exports = {
main: function(req, res){
res.render('index')
},
contact: function(req, res){
res.render('contact')
},
algorithms: function(req, res){
res.render('algorithms')
},
projects: function(req, res){
res.render('projects')
},
other: function(req, res){
res.render('default')
},
}
I have a current front-end only Angular 2 application using the Angular-CLI and NPM. I want visitors to be able to send me emails through the contact form.
For this I obviously need a back-end, express and node, in which I have no experience in using.
I need to intergrate express and node into my app but I dont know how to do this correctly.
I have found THIS similar question on SO but its not relevant to my situation.
Other tutorials only show how to scaffold a MEAN stack app not intergrate the backend after the front end has been built.
What I would like to know:
How do I set up my Angular 2 App to use express and node for the back end?
What are the relevant files I need?
Can I do this by using the Angular-CLI?
The best way to setup a project that is built using angular-cli to use a nodejs/express backend is to simple create an express project that serves up a directory. In your client project, if it has been created using the angular-cli, you should be able to just type in ng build and it will compile everything into a dist directory.
From there, you can create an express server that serves up that dist directory like so:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
The most simple server you could build would probably something like
var express = require('express')
var path = require('path');
var app = express()
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
This will intercept all routes and redirect them to the index.html file in the dist/ folder that was created.
For more information on how to set this up and some more advanced settings, check out these links:
http://expressjs.com/en/starter/installing.html
https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli
Just think about the dist/ folder as static files that will be served over an express server, and because routing and everything is handled through angular, you'll be set.
I am building an app using node.js + express.js + react.js and I'm using webpack to compile the client side code. The problem I am having is after my client side code is compiled with webpack and I run my app, I cannot refresh the page.
My code:
My webpack compiles my files into /dist/index.html, my app runs on port 3000, and all client side routes are prefixed with /admin.
app.get('/', function(req, res) {
res.render('dist/index.html');
});
When I go to localhost:3000 in the browser and click around the links, the app works fine. However, if I go to, as an example, the about page:
localhost:3000/admin/about
And I refresh, I get the error Cannot GET /admin/about.
I believe the reason is my express router only knows about the / route... so If I refresh directly onto a route like /admin/about, express doesn't know what to render so my solution was to include a "catch all" route:
app.get('*', function(req, res) {
res.render('dist/index.html');
});
However, this keeps giving me the Error: Failed to lookup view "dist/index.html" error.
Can someone help?
Thanks in advance!
After research, I found the solution isn't res.render but res.sendFile:
res.sendFile(path.join(__dirname, '/dist/index.html'));