fullstackreact / food-lookup-demo Goto Github PK
View Code? Open in Web Editor NEWA demonstration of using `create-react-app` with a server
License: MIT License
A demonstration of using `create-react-app` with a server
License: MIT License
I'm not sure how much legwork an https example would require, but it would go much appreciated.
Given that I'm using Heroku's new Automated Certificate Management, what specifically would need to change within the provided server.js
and the Client.js
's fetch calls to make this work?
While in production, I'm using this within server.js
to re-route everything through https.
app.use((req, res, next) => {
if (req.header['x-forwarded-proto'] !== 'https')
res.redirect(`https://${req.header('host')}${req.url}`)
else
next()
})
Though, this produces CORS problems.
One issue I foresee here is that the documentation indicates:
The API URL in development matches that in production.
Which, since I do not need to setup a ssl certificate for local development, indicates I might need to do something like this:
const apiBaseUrl = process.env.NODE_ENV === 'development' ? 'localhost:3001' : '?'
Though I'm not sure how to make this all fit together with fullstackreact's existing setup.
Thanks
Hi there,
Love the blog/repo, very informative. I'm currently trying to deploy an app to a single Heroku dyno which does not use create-react-app but has an express server for webpack and a rails API backend.
I'm having issues getting express to proxy my requests to the API (but works fine locally), here is the error from Heroku logs:
2017-12-03T16:00:18.436271+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3005
2017-12-03T16:00:18.436308+00:00 app[web.1]: at Object.exports._errnoException (util.js:1018:11)
2017-12-03T16:00:18.436309+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:1041:20)
2017-12-03T16:00:18.436311+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
I made sure to use buildpacks for both node and rails as described here.
Here is the relevant code:
Procfile
web: npm run start:prod
api: bundle exec rails server --port=3005 --environment=production -b 127.0.0.1
package.json
{
"name": "stage_sidekick_v2",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"proxy": "http://127.0.0.1:3005/",
"engines": {
"node": "6.10.2",
"yarn": "0.24.5",
"npm": "5.5.1"
},
"scripts": {
"start": "NODE_ENV=development node server",
"start:prod": "yarn run build && NODE_ENV=production node server",
"build": "NODE_ENV=production webpack -p --config ./webpack.prod.js --progress --colors --display-error-details"
},
server.js
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
const port = process.env.PORT || 3000;
const path = require('path')
const webpack = require('webpack')
const proxyHost = '127.0.0.1';
const proxyPort = '3005';
app.use('/api', proxy(`${proxyHost}:${proxyPort}`));
const isProd = process.env.NODE_ENV === 'production'
let config
if (isProd) {
config = require('./webpack.prod.js')
} else {
config = require('./webpack.dev.js')
}
const publicPath = config.output.publicPath || '/';
const outputPath = config.output.path || path.resolve(process.cwd(), 'dist');
if (!isProd) {
console.log('Development env detected: Initializing hot reloading')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const compiler = webpack(config)
app.use(webpackHotMiddleware(compiler, {
log: console.log,
path: '/__webpack_hmr'
}))
app.use(webpackDevMiddleware(compiler, {
entry: config.entry,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}))
app.use('*', function (req, res, next) {
const filename = path.join(compiler.outputPath, 'index.html')
compiler.outputFileSystem.readFile(filename, (err, result) => {
if (err) {
return next(err)
}
res.set('content-type', 'text/html')
res.send(result)
res.end()
})
})
} else {
app.use(publicPath, express.static(outputPath));
app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html')));
}
app.listen(port, (err) => {
if (err) {
console.log(err.message)
} else {
console.log(`Server Started at port ${port}`);
}
});
Any help would be greatly appreciated!
Error code below:
> babel-node server.js
sh: babel-node: command not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] server: `babel-node server.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /somePath/debug.log```
Seems like both react
and react-dom
dependencies are missing in the latest client package.json
, or is there anything I'm missing?
Can someone please explain how the server is being bundled up to the heroku end of things? Seeing that its only the build that's deployed
Your config has been working great so far locally. When i deployed it to Heroku i started getting the following issue:
If i go to https://enjoy-copenhagen-dev.herokuapp.com everything is fine, i can navigate through the app, no issues there.
If i go to https://enjoy-copenhagen-dev.herokuapp.com/api or whichever one of my api post and get endpoints everything works.
If i try to open any other route i get Cannot GET /route-i-tried-to-open
.
My server.js
const cors = require('cors');
const path = require('path');
const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const app = express();
const mail = require('./emailSenders');
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
// support json encoded bodies
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: false }));
app.set('port', process.env.PORT || 3001);
// Express only serves static assets in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
app.get('/api', (req, res) => {});
app.post('/api/createCustomer', (req, res) => {});
app.post('/api/retrieveCustomer', (req, res) => {});
app.post('/api/createCharge', (req, res) => {});
app.post('/api/sendEmail', (req, res) => {});
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`); // eslint-disable-line no-console
});
package.json
{
"name": "lookup-server",
"version": "0.0.1",
"private": true,
"dependencies": {
"babel-core": "6.14.0",
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"ejs": "^2.5.7",
"email-templates": "^3.5.2",
"express": "4.13.3",
"fs": "0.0.2",
"node-schedule": "^1.3.0",
"nodemailer": "^4.4.2",
"sql.js": "0.3.2",
"stripe": "^5.4.0"
},
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\"",
"server": "node server.js",
"client": "node start-client.js",
"dev": "echo \"This command has been deprecated. Use 'npm start'\" && exit 1",
"lint": "eslint ."
},
"devDependencies": {
"concurrently": "3.1.0",
"eslint": "^3.19.0",
"eslint-config-airbnb": "14.1.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "4.0.0",
"eslint-plugin-react": "6.9.0"
}
}
Please help me fix this!
I am trying to extend this project to serve new files and am running into major issues. for example if I add this to routes/index.js:
app.route('/login')
.get(function (req, res) {
res.sendFile('./client/public/login.html', { root: __dirname });
});
the dirname is just completely wrong and nothing I can do helps (i've tried everything including adding path.resolve). Bottomline is it really doesnt look like this route is run on the server at all. this suspicion is further confirmed if I mess around with the '/' route:
app.route('/')
.get(function (req, res) {
res.sendFile(bipath.join(__dirname, '../public', 'THISCANBEANYRANDOMFILENAME.html'))
});
and the app still works fine because you configured webpack so that "All requests to localhost:3000
will serve `client/index.html". How did you do that!
So really i have two questions here. Hope i made sense. I also logged this on SO: http://stackoverflow.com/questions/41859154/webpack-somehow-bypasses-express-routing-completely
Your food-lookup-demo puts only the static portion ( the react app setup by create-react-app ) to heroku , what about the api server on port 3001
[email protected]
honors process.env.PORT
when you run npm start
.
For some reason it gets set to 5000
(is Foreman doing it?)
However the CORS headers are enabled for 3000
.
So you’d either need to change npm start
to PORT=3000 npm start
(not cross-platform btw), or make it cross-env PORT=3000 npm start
(cross-platform but needs cross-env
dependency), or somehow configure Foreman to ask it to be on 3000
, or just set CORS headers to use 5000
.
➜ food-lookup-demo git:(master) ✗ npm run server
> [email protected] server /Volumes/caicloud/lab/food-lookup-demo
> node server.js
/Volumes/caicloud/lab/food-lookup-demo/server.js:62
);
^
SyntaxError: Unexpected token )
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
npm ERR! Darwin 16.6.0
npm ERR! argv "/Users/yangzi/.nvm/versions/node/v6.9.4/bin/node" "/Users/yangzi/.nvm/versions/node/v6.9.4/bin/npm" "run" "server"
npm ERR! node v6.9.4
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] server: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] server script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the lookup-server package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs lookup-server
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls lookup-server
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Volumes/caicloud/lab/food-lookup-demo/npm-debug.log
It seems that the server scripts has some syntax wrong, please have a look.
Hello, I am rather inexperienced with both react and fullstack. I am following the blog post step by step, early on I get to the point of running npm run server
and it does without error.
But when I open localhost:3001 in my browser, instead of seeing the server as shown in the images of the blog, I see:
Before exiting the npm run server
command, I called curl in a separate window and also got:
I'd like to point out that everything else went according to the blog's directions EXCEPT that neither npm start
nor npm run server
opened a browser tab on its own the way npm start
does for create-react-app project. i had to type localhost:3000 and localhost:3001 for runs of start and run server respectively, and only had an issue with 3001/run server.
Any help troubleshooting would be much appreciated, again I'm rather inexperienced so if there's a better way to ask or any obvious resources I can be pointed towards, that would be helpful as well. Thank you!
Environment
macOS Sierra 10.12.1
bash-3.2$ nvm --version
0.32.1
bash-3.2$ which npm
/Users/jason/.nvm/versions/node/v7.2.0/bin/npm
bash-3.2$ node --version
v7.2.0
Steps to reproduce
Expected Result
API endpoint should return json
Garbage URL should return error
Actual Result
Search does not complete. All endpoints return the index page.
i'm at the very beginning of this project. after installing npm packages and typing npm start
, i get the following in the console:
> concurrently "npm run server" "npm run client"
[0]
[0] > [email protected] server /Users/tamenze/Desktop/newDuck/food-lookup-demo
[0] > node server.js
[0]
[1]
[1] > [email protected] client /Users/tamenze/Desktop/newDuck/food-lookup-demo
[1] > node start-client.js
[1]
[1]
[1] > [email protected] start /Users/tamenze/Desktop/newDuck/food-lookup-demo/client
[1] > react-scripts start
[1]
[0] Find the server at: http://localhost:3000/
[1] Something is already running on port 3000.
And the view shows a "Cannot GET /" I've checked and nothing else is running on that port, and I've even used lsof -i tcp:3000
, to no avail.
And When I exit npm, I get the following error:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `concurrently "npm run server" "npm run client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
hi All,
i am trying to Create a project through Create-react-app boilerplate then add a Backend Folder in Src and add Express Server With Name Server.js Inside That Backend Folder.
Now i am Adding A Custom Script in Package.json Which is in Root Folder . Now Starting node Server and React App both but Both Together is not Starting ... ! so Can Any one help me
Hi;
I used your tutorial as a start point and I successfully created an app and managed to get data with fetch
My problem is that I used krakenjs
as my nodejs backend and it has default security rules set. I don't want to disable CSRF but when I try to do a POST request with fetch I get CSRF Token missing
error.
I couldn't find a solution with doing some google search. I tried to save 'x-csrf-token' header on localStorage and post it back when I make a fetch POST but then I got CSRF Token mismatch
error.
I would really appreciate any help or suggestions.
Thank You
Hi. Just had a new React learner ask a question about the code in this demo, and I'm a bit concerned about some of the approaches being used. These are semi-stylistic concerns, but I think that fixing them would improve the learning experience and usefulness for someone trying to read this sample.
In particular, looking at App.js, there's several things I would suggest changing:
onFoodClick
in both child components are being defined inline in the JSX. This is an issue for two reasons:render
is generally discouraged as a poor performance pattern. It's certainly not going to be a real perf issue here, but there's no actual reason to define the callbacks inside of render
here at all.render
, they're completely inline - not even being assigned to a temporary variable name earlier in render
. This makes it very hard to see what the logic is, and makes the render
method much harder to read.App
component is being defined using the older-style React.createClass
syntax. This still works, but long-term is going to be deprecated. The React team recently rewrote the React docs, and updated all the examples to use ES6 classes, so it would make sense to follow suit here.onFoodClick
callback, which appears to be trying to remove an item from the selectedFoods
array, is using a very verbose method for doing so: the "double slice" technique. I personally am not a fan of that approach, and would suggest using a call to Array.filter
instead. In this case, that would be something like this.state.selectedFoods.filter( i => i !== idx)
.None of these are absolutely life-and-death, but I think these fixes would definitely improve the readability
here is my code for index.js :-
const express = require('express')
require('./db/mongoose')
const userRouter = require('../src/routers/userRouter')
const taskRouter = require('../src/routers/taskRouter')
const app = express()
const port = process.env.PORT
// app.use((req,res,next)=>
// {
// res.status(503).send('App under maintainance')
// })
app.use(express.json())
app.use(userRouter)
app.use(taskRouter)
app.listen(port,()=>{
console.log('Server is up and running on port ',port)
})
For userRouter :-
const express = require('express')
const User = require('../models/user-model')
const router = new express.Router()
const { deletemsg } = require('../../email/deletemsg')
const {welcomeEmail} = require('../../email/account')
const sharp = require('sharp')
const auth = require('../middleware/auth')
const multer = require('multer')
router.post('/users',async (req,res)=>{
const user = new User(req.body)
try{
await user.save()
welcomeEmail(user.email,user.name)
const token = await user.generatejwt()
res.status(201).send({user,token})
}catch(e){
res.status(404).send()
}
})
router.post('/users/login',async (req,res)=>
{
const user = await User.findbyCredentials(req.body.email,req.body.password)
const token = await user.generatejwt()
if(!user)
{
return res.status(400).send('Unable to login')
}
res.status(200).send({user,token})
})
I have had nothing but trouble getting other, similar demos to work, yours is the first one that has worked (almost) immediately, I just had to tweak a couple of things and it was up and running!
The one thing that is noticeably different than all of the (probably up to 12) other demos I have downloaded and gave up in frustration, is the start-client.js
file. I can tell it is doing something critical to the proxy, and that is where my problem always was in the other demos, so I really want to understand exactly how this piece works.
I was confused at first because the naming of things in the package.json
- we have concurrently calling npm run server
and npm run client
, which makes sense, because two lines down there is a client
script that is calling a start-client.js
script. But that seems to be pointing back to the client
in one of the parameters, which at first looks like a closed circuit.
But then, I saw that there is a top-level directory named client
as well, with its own package.json, and a start script... is the client being pointed to in the start-client.js
script? Does it not need any more information than that, just the directory name?
Also, what are all the other params in that script doing? Mostly this part here: {stdio: 'inherit', cwd: 'client', shell: true}
?
Thank you for doing such a great job with this! Extremely well documented and commented throughout the code, very helpful!
It looks like eslint@^3.19.0
is a required peer dependency for the package [email protected]
. Is it appropriate to change the top-level package.json
file to include "eslint": "^3.19.0"
instead of "eslint": "3.15.0"
?
Whenever I run npm run server it gives me this error. I have googled it a lot but haven't found the solution. what should i do?
module.js:487
throw err;
^
Error: Cannot find module 'sql.js'
at Function.Module._resolveFilename (module.js:485:15)
at Function.Module._load (module.js:437:25)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object. (C:/Users/ATUL/Documents/GitHub/food-lookup-demo/server.js:3:16)
at Module._compile (module.js:569:30)
at loader (C:\Users\ATUL\Documents\GitHub\food-lookup-demo\node_modules\babel-register\lib\node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (C:\Users\ATUL\Documents\GitHub\food-lookup-demo\node_modules\babel-register\lib\node.js:154:7)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] server: babel-node server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\ATUL\AppData\Roaming\npm-cache_logs\2017-08-25T18_50_06_252Z-debug.lo
I'm trying to use this boilerplate for my new project but somehow on my way to development it is not watching the files when saving it. Any help will appreciated guys, thanks!
Right now, our boot command for the client app is this (in Procfile.dev
):
cd client && npm start
This does not work in Windows. We can use Node to perform the invocation, like:
// in package.json
"start": "start-client.js",
// in start-client.json
// something like ...
node.cwd('client'); require('child_process').spawn('./node_modules/.bin/npm', ['start']);
I need to implement and test this on both platforms.
I Cannot GET /register on heroku server error , it send 404 bad request
`const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const cors = require('cors');
const knex = require('knex');
const register = require ('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
connectionString: process.env.DATABASE_URL,
ssl: true,
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/',(req,res) => {res.send('it is Working!')})
app.post ('/signin', signin.handleSignin(db,bcrypt))
app.post('/register',(req,res) => { register.handleRegister(req,res,db,bcrypt)})
app.get('/profile/:id',(req,res) => {profile.handleProfileGet(req,res,db)})
app.put('/image',(req,res) => {image.handleImage(req,res,db)})
app.post('/imageurl',(req,res) => {image.handleApiCall(req,res)})
app.listen(process.env.PORT || 3000, () => {
console.log(app is running on port ${process.env.PORT}
);
})`
`
const handleRegister = (req,res,db,bcrypt) => {
const {email,name,password} = req.body;
if (!email || !name || !password){
return res.status(400).json('incorrect form submission');
}
const saltRounds = 10;
const hash = bcrypt.hashSync(password,saltRounds);
const salt = bcrypt.genSaltSync(saltRounds);
db.transaction(trx => {
trx.insert({
hash : hash,
email : email
})
.into ('login')
.returning('email')
.then(loginEmail => {
return trx('users1')
.returning('*')
.insert ({
email : loginEmail[0],
name : name,
joined : new Date()
})
.then (user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister : handleRegister
};
`
server_file.txt
registerfile.txt
Sorry if this is the wrong place to ask this question...
I followed your tutorial, and have been pouring over all your files to see where I might have messed up. But for some reason, I can't get it to work. It will only launch my server side but won't use the client/build to deploy static files.
I don't see what it is I'm doing wrong, It works great locally.
Also the logs on heroku haven't been much help.... not saying much.
Here is my repo: https://github.com/codepressd/salut
Any insight would be much appreciated.
Chris
So I wanted to see if I could get full stack debugging in VSCode working with this project and I think I've made a working launch script:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Server",
"program": "${workspaceFolder}/server.js",
"cwd": "${workspaceFolder}"
},
{
"name": "Client",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/client",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/src/*"
}
}
],
"compounds": [
{
"name": "Server/Client",
"configurations": ["Server", "Client"]
}
]
}
Now when I run the server/client debugging combination (after running npm start
in the client
folder), with this config I am able to put breakpoints in client API calls and their corresponding express API routes; both of these breakpoints are successfully hit.
I was wondering if you would consider including this launch script in your project (perhaps in the README?). At least in my case, it makes the debugging experience a lot easier for VSCode, which I assume is quite commonly used.
run
cd food-lookup-demo/client
npm i
got
npm WARN deprecated [email protected]: breaking changes from clean-css 4.x. Please install gulp-clean-css 3.x
npm ERR! fetch failed https://github.com/derekslife/wrench-js/tarball/156eaceed68ed31ffe2a3ecfbcb2be6ed1417fb2
npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404
npm ERR! fetch failed https://github.com/derekslife/wrench-js/tarball/156eaceed68ed31ffe2a3ecfbcb2be6ed1417fb2
npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404
npm ERR! fetch failed https://github.com/derekslife/wrench-js/tarball/156eaceed68ed31ffe2a3ecfbcb2be6ed1417fb2
npm ERR! Darwin 16.6.0
npm ERR! argv "/Users/yangzi/.nvm/versions/node/v6.9.4/bin/node" "/Users/yangzi/.nvm/versions/node/v6.9.4/bin/npm" "i"
npm ERR! node v6.9.4
npm ERR! npm v3.10.10
npm ERR! fetch failed with status code 404
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
npm ERR! /Volumes/caicloud/lab/food-lookup-demo/client/npm-debug.log
if I remove the dependency of semantic-ui
, the install process will run well.
How will I integrate socket.io?
I want to broad-cast message server from client, So what will be good solution for that?
Hi and thanks for the tutorial I am following here: https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/
I was wondering what was the start-client.js
file during my reading and I found out here that it is just a wrapper for npm start --prefix client
.
Why did you do that?
Many of the dependencies are now badly deprecated. To the point that npm fails miserably.
As I'm interested in the client+server unified deploy, I edited client/src/index.js and commented out the following line:
// import "../semantic/dist/semantic.min.css";
Then I was able to "yarn install" (npm failed).
The application started, unstyled.
IMO the client+server unified deploy deserves a lifting, so other developers don't waste a lot of time as I did.
REgards!
Dear author(s),
first of all, thanks for the great tutorial and repo, very appreciated! What I am missing is a LICENSE, though. As it is clearly meant to be reused, something like an MIT-license for the whole repository would be great, as otherwise nobody is able to use your work in their own projects. Thanks and once again, great work!
Thanks a lot for great tutorial.
However, what I strongly miss is any clue how to use given infrastructure with an authorisation controlled by the API server.
Scenario:
/protected-page
from client
(React app) shows by default login form or something similarprotected-page
contentCould you provide me any hint please? Or even better, enhance the tutorial accordingly as I'm for sure not alone with this request.
Thanks.
Hi,
I am new to react, Express and nodejs. I was wondering how to deploy the app manually to a server. Should I run the build script inside the client folder and then past the files within the server along with the server file?
Thanks
João
I saw this issue already, but as i don't see how building the client might cause the error i decided to create a new issue.
The only modifications i've made to your structure is i've put the server files in "/server" and not in the root of the app.
The problem
When i run npm start
and the server and client starts, when i make any request to the server i get the error:
[1] Proxy error: Could not proxy request /api/sendEmail from localhost:3000 to http://localhost:3001/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
Any idea what is causing this and how i can fix it?
FYI the issue happens only when i run the server locally. On the deployed version at Heroku everything works.
Server package.json
{
"name": "lookup-server",
"version": "0.0.1",
"private": true,
"dependencies": {
"babel-core": "6.14.0",
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "4.13.3",
"fs": "0.0.2",
"node-schedule": "^1.3.0",
"nodemailer": "^4.4.2",
"sql.js": "0.3.2",
"stripe": "^5.4.0"
},
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\"",
"server": "node server/server.js",
"client": "node start-client.js",
"dev": "echo \"This command has been deprecated. Use 'npm start'\" && exit 1",
"lint": "eslint ."
},
"devDependencies": {
}
}
Client package.json
{
"name": "enjoy-copenhagen",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:3001/",
"dependencies": {
},
"scripts": {
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build-js": "react-scripts build",
"build": "npm-run-all build-css build-js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
}
}
This didn't work for me:
git clone [email protected]:fullstackreact/food-lookup-demo.git
This did work for me:
git clone https://github.com/fullstackreact/food-lookup-demo.git
Sorry, just a drive-by jackass here :-)
Isn't there a SQL injection flaw here? https://github.com/fullstackreact/food-lookup-demo/blob/master/server.js#L32
const r = db.exec(`
select ${COLUMNS.join(', ')} from entries
where description like '%${param}%'
limit 100
`);
That will interpolate the variable param
, which comes from the query string, directly in the SQL string.
Hi!
How can I reload(?) the server, every time I change server code? Like how it is done for the react app
Upgrading to "babel-core": "^6.6.5" removes the npm i
warning.
After reaching the step to run npm start at the top-level directory, I'm met with this error:
ReferenceError: Unknown plugin "transform-class-properties" specified in "/Users/scottmarlatt/.babelrc" at 0, attempted to resolve relative to "/Users/scottmarlatt"
Both babel-node server.js
and babel-node start-client.js
are failing. Can provide debug logs if needed, but I wasn't seeing anything useful. Is there something I am supposed to do with configuring babel that isn't mentioned in the readme?
I installed the app on and when I run it there is no data showing? Running on mac os Sierra in latest Chrome.
Thanks for this project. I love the clear way the project shows how to graft a server onto create-react-app.
"proxy": "http://localhost:3001/"
to the client's package.json file. Will you update the article at https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/ to reflect this? It would be great to have a brief description of how the proxy
works, as well...allowCrossDomain()
middleware in the original article. Perhaps a new article?Many thanks!
The description on deployment mentions that in production npm run server
should be run.
But there is a downside to this: npm run server
invokes babel-node
. It would be nicer to have – like create-react-app – a production build that does not need babel
anymore but can be run with plain Node.JS.
Everything works fine except the automatically restarting server and client is not working anymore. Should use nodemon? If so how about client?
I've cloned the repo, everything is working fine, but after runing npm run build and running a prod version of clinet - it looks like we are loosing connection between client and API.
Any ideas how to fix that?
Can someone suggest how one would go about adding react-router
v4 to the mix so that react handles all the routes other than /api/*
.
Firstly, thank you for this project!
After upgrading to react-scripts >= 8.0 and executing npm start
, the browser no longer launches automatically. This happens with foreman as well as concurrently.
Any ideas?
Thanks much!
Been trying to make an app very similar to this. However, when deploying to Heroku without a HOST file I get "Invalid Host Header" on the react app. When adding a HOST I get an error from the Heroku logs.
Just curious how you've avoided this issue. Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.