Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create-react-app with node express getting %PUBLIC_URL%

I'am trying create-react-app with express server. after setting server when I hit request I'm getting

GET http://localhost:3333/%PUBLIC_URL%/favicon.ico 400 (Bad Request)

On error preview its giving me

URIError: Failed to decode param '/%PUBLIC_URL%/favicon.ico'
    at decodeURIComponent (<anonymous>)
    at decode_param (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:172:12)
    at Layer.match (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:123:27)
    at matchLayer (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:574:18)
    at next (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:220:15)
    at jsonParser (/home/owaishanif/code/flashcard-app/node_modules/body-parser/lib/types/json.js:103:7)
    at Layer.handle [as handle_request] (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:317:13)
    at /home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/owaishanif/code/flashcard-app/node_modules/express/lib/router/index.js:335:12)

Here is the Server Code

var express = require('express');
var bodyParser = require('body-parser');
var path = require ('path');

var data = {};

express()
    .use(express.static(path.resolve(__dirname, '..', 'public')))
    .use(bodyParser.json())

    .get('/api/data', (req, res) => res.json(data))

    .post('/api/data', (req, res) => res.json(data = req.body))

    .get('*', (req, res) => res.sendFile( path.resolve( __dirname, '..', 'public/index.html')))

    .listen(3333, function(){
        console.log('server running at 3333');
    });

I want to use create react app with server. There are articles online but they are outdated. Help tips and tricks are welcome.

like image 806
bawa g Avatar asked Jul 01 '17 15:07

bawa g


1 Answers

I have solved this using create-react-app build which creates a build folder. also %public_url% string is replaced by some yarn scripts behind the scenes. So we cant directly serve that folder. Instead we have to generate using build.

Use yarn build or npm run build. That will generate a build folder containing asset, manifest, and other files.

After that, use that build folder to statically serve your files for production use.

like image 65
bawa g Avatar answered Nov 07 '22 07:11

bawa g