My app works fine in webpack development server. Now, I want to deploy it to my production server. So I built bundle.js. I tried serving the file on express server, but I can't access urls other than the root /.
For example, here is my react routes:
var Routes = () => (
<Router history={browserHistory}>
<Route path="/" component={Landing}>
</Route>
<Route path="/app" component={App}>
</Route>
</Router>
)
and express app (I put bundle.js and index.html in ./public):
app.use(express.static('./public'));
app.listen(port, function () {
console.log('Server running on port ' + port);
});
Landing page http://localhost:3000/ works. But the app http://localhost:3000/app doesn't. Instead, I got an error Cannot GET /app.
You need to declare a "catch all" route on your express server that captures all page requests and directs them to the client. First, make sure you're including the path module on your server:
var path = require('path');
Then, put this before app.listen:
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
This assumes you're inserting bundle.js into index.html via a script tag.
Related
Scenario:
I am making a basic web app using Vite & Tailwind. I set up my app as normal installing Vite, and Tailwind, and got everything running fine by testing for Tailwind css on localhost:5500.
Problem:
Once I added an Express server to the mix, and it sends the index.html in response to a 'GET' request # '/', I no longer get the compiled CSS from tailwind.
Is this an uncommon setup that should be troublesome?
You could possibly use a middleware like express.static
Example:
const express = require('express')
const app = express()
app.use(express.static(__dirname + '/public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
In this example, the express.static middleware is used to serve the public directory, which is where the compiled CSS files from Tailwind will be located. Then the express server will send the index.html file in response to a GET request at the root '/' path.
Extra: Alternatively you can also use Webpack or Parcel , which can automatically handle the process of bundling and serving your CSS files
I set a public path in vue.config.js like
module.exports = {
publicPath: '/subpath'
};
it works fine when I start the devlopment server with npm run serve (vue-cli-service serve). The app becomes available at localhost:8080/subpath which is exactly what I want. It uses vue-router and at least in development it seems to work perfekt with the /subpath as publicPath.
Problem
I am using Express to serve the app files. Running npm run build the app will be built and stored to ./dist folder (default output folder).
// simplified server.js
app.use(express.static(path.join(__dirname, '/dist')));
app.get('/', (req, res, next) => {
res.sendfile('./dist/index.html');
});
After starting my express server and visiting my browser at localhost:<port>/subpath or localhost:<port> it can't find the necessary files.
// EXAMPLE FROM BROWSER CONSOLE
GET http://localhost:5050/subpath/js/app.6c6daa90.js net::ERR_ABORTED 404 (Not Found)
Which somehow looks obvious to me but I don't know how to set the express server correctly to respect the publicPath setting . Maybe there is a different approach ?
Attempt #1
I made a little change in my express server.js
// app.use(express.static(path.join(__dirname, '/dist')));
/* NEW */
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
This way it should serve the static files from the /dist folder when requested with /subpath/app.js
Result
From Browser console when requesting localhost:<port>/subpath or localhost:<port>
Refused to load the font 'data:application/font-woff2;base64,<omitted>' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://localhost:5050/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
I played around with express.static and this combination seems to work for me
const path = require('path');
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static(path.join(__dirname, '/dist')));
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
const listener = app.listen(5050, () => {
console.log(`Open http://localhost:${port} in your browser`);
});
Sidenote : Adding connect-history-api-fallback was not required to solve the initial problem but is required for vue-router to work properly when in history mode.
Hello
I have an express app running as a REST server, meaning all the /api/xx routes are process in express.
I also have a react app (served by express when accessing the /) as a client, which also has a router, the problem comes when i refresh a react route, the 404 page error of express shows up instead of the react page itself.
The react router
<Router history={browserHistory}>
<Route path="/" component={MainLayout} user={user}>
<IndexRoute component={DocumentsPage}></IndexRoute>
<Route path="about" component={AboutPage}></Route>
<Route path=":id/preview" component={PreviewPage}/>
<Route path="upload" component={UploadPage}></Route>
</Route>
</Router>
and when i access with a <Link to="upload" </Link> the page shows up, and when i refresh the page, i got the 404 express's page..
Any help would be lovely <3
You need to configure a fallback, so that every request that doesn't exist in your Express routing is redirected to your React app at /. Here's a basic example of how to do that with Express:
import fallback from 'express-history-api-fallback';
import express from 'express';
import http from 'http';
// Set up express
const app = express();
const server = http.createServer(app);
const root = `${__dirname}`;
// History Fallback for express
app.use(express.static(root));
app.use(fallback('index.html', { root }));
// Listen
server.listen(8080, '0.0.0.0');
Then you can also handle your 404 page with React Router.
OK, I'm still trying to build react.js app with server side rendering. I having big time dealing with react-router with parameters. I cannot extract routes params from route on server side to make proper query on DB.
Here is my react-router route:
import {Router,Route} from "react-router";
import React from "react";
import App from "../components/app";
import {HomeContainer} from "../components/home";
import {TagContainer} from "../components/tag";
export function createRouter(hist) {
const routes = <Route component={App}>
<Route path="/" component={HomeContainer}/>
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
</Route>;
return (
<Router history={hist}>{routes}</Router>
);
}
the route run fine until I add parameter ":unique_name" to the route
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
on the server side, I cannot extract unique_name from the route to make query on DB:
Here is the route on server(Using Node.js & Express.js):
const router = express.Router();
router.get("/tag/:unique_name", ServerRenderController.tagRender);
server.use(express.static(path.join(__dirname, '..', '/build')));
server.use(router);
and here is my "ServerRenderController.tagRender":
function tagRender(req, res) {
console.log(req.params.unique_name);
/*
output :
mytag_unique_name -> this is the route params
style.css ->stylesheet - how the hell it become route params?
app.js -> client code - how the hell it become route params?
vendor.js -> vendor scripts - how the hell it become route params?
manifest.js -> manifest file -how the hell it become route params?
*/
match({browserHistory,routes, location:req.url}, (err, redirectLocation, renderProps)=> {
if (redirectLocation) {
//#TODO: response redirect location
console.log('redirect location');
}
if (err) {
//#TODO: response error
console.log(err.stack);
}
if (!renderProps) {
//#TODO: route to 404
console.log("no renderProps");
}
renderPage(renderProps); // return HTML to client with __PRELOADED_STATE__
}
Questions :
What did I do wrong in server code (routing, express static
middleware...).
How do I extract correct route params from route? (I only want to extract "mytag_unique_name" as the only params when I browse to http://localhost/tag/mytag_unique_name)
right now the route params including static files that should be
send as MIMETYPE css/js.
OK. Turn out I made mistake in references to style sheets and scripts file.
In the server render code must refer <link href="/style.css" rel="stylesheet"/>
with slash (/) at the begining of the rel attr.
Note here for anyone have same problem.
I am using Express and React to build an isomorphic app. I want to use react for a series url with fixed path like: hostname/admin/xxx, hostname/admin/yyy, hostname/admin/zzz.
In Express the router is:
// in server.js file
app.use('/admin', admin);
// in admin.js router file
router.get('*', (req, res) => {
match() // react-router's match method
}
and in the react-router's routes file it is:
<Route path='/' component={Admin}>
<Route path='child' component={Child} />
</Route>
When I visit hostname/admin, the server rendering can match the routes exactly, but the browser thrown an error: Warning: [react-router] Location "/admin" did not match any routes.
If I change the routes to
<Route path='/admin' component={Admin}>
<Route path='child' component={Child} />
</Route>
the server rendering cannot match any routes.
I think the problem is, for server rendering, the path is '/', but for client it is '/admin'. How can I fix it except using app.use('/', admin) in Express?
My final solution is add '/admin' to the location property in match() method:
match({
routes,
location: '/admin' + req.url
}, (error, redirectLocation, props) => {
});