vasansr / pro-mern-stack Goto Github PK
View Code? Open in Web Editor NEWCode Listing for the book Pro MERN Stack
Home Page: http://www.apress.com/in/book/9781484226520
Code Listing for the book Pro MERN Stack
Home Page: http://www.apress.com/in/book/9781484226520
Hey, I love your book, especially the well thought out exercises; they are all too rare in programming books.
I just started reading, so forgive me if I am jumping the gun, but I want to see what the final product will be like. The problem is I can not run the server.
Ubuntu 16.04
node: v4.5
npm -v 2.15.9
npm install in /pro-mern-stack (master)
npm start in /pro-mern-stack (master)
I get error
can't find dist/server.bundle.js
Thanks for the great book and any help you can give me so I can preview the end product of the book!
This method does not seem to work with const in the for loop and const on type. I removed both const references and it begins to capture missing required fields besides id.
after i installed the babel-cli, the babel command is not found. I tried to manually install the .babelrc with the presets but when I change the the html file to reflect the /App.js the page is blank.
I'm making the assumption the cmd babel src --presets react --out-dir static creates the App.js automatically?
please advised ... oh i'm using a Mac with Sierra 10.12.5
this is what is in my babel file
cat babel
#!/usr/bin/env node
require("../lib/babel");
i tried this since it's a script
./babel src --presets react --out-dir static
and now i get src doesn't exist
Thank you.
Angel
I was following great until all of the substantial project restructuring and middleware added in chapter 7, at which point my project stopped running properly. I cloned a copy of the code as per the end of chapter 7 from the relevant branch on this repository, but I still get the very same error.
Running npm run dev-all
, which chains npm run watch & npm run watch-server & npm start
, now gives me the following error in the console when I try and load the application:
[HPM] Error occurred while trying to proxy request /api/issues from localhost:8000 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
The node.js documentation suggests that "this usually results from trying to connect to a service that is inactive on the foreign host." So the Express server on :3000 isn't running? I definitely have mongod.exe listening for connections.
Any pointers would be greatly received, thanks!
Running the "npm run watch" command could cause an error. Pay attention to the notes in the error as seen blow
Error: Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options
object or the name of the chunk.
Example: if your old code looked like this:
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js')
You would change it to:
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
On page 46, the example of wrapping any component with a border reads as:
<BorderWrap>
<Example>Component />
<Bordewrap>
Should be:
<BorderWrap>
<Example>Component />
<Borderwrap>
to use react-router v^2.7 you must install react-router-bootstrap@rr-v3
https://github.com/react-bootstrap/react-router-bootstrap/tree/rr-v3
whenever retrieving data from database, by using the latest mongodb package throws error but the previous version of mongodb 2.2.33 works perfect so it should change in package.json
Location.query doesn't work with react-router 4.
So instead of using location.query
install query-string
$ npm install --save-dev query-string
Add it to webpack.config and import it into your IssueList (or whatever file)
import queryString from 'query-string';
then use
queryString.parse(this.props.location.search)
I'm a bit new to react but in other tutorials--they used create react app and there was no need to compile jsx files. Can someone explain if this way of doing things is preferred?
After I added the "compile": and "watch": to under "scripts": in package.json, I run 'npm run compile' and I see the change 'src/App.jsx -> static/App.js in my terminal. That runs just fine.
But the next step, I made a small change to the var component =
The only time I get any change is when I make changes to the App.js file in the var component =React.createElement('h1', null, 'Hello World');
Is the npm watch supposed to make live changes to the browser?
UPDATE:
It all works when I make changes to the App.jsx file THEN npm run compile FOLLOWED by npm run watch. After that, I refresh my browser and the changes are made!!
On page 30 at the top it specifically says "Go ahead and run the new command npm watch". While it does make one transform and doesn't return to the shell, the next part of the paragraph states to make the small changes to App.jsx and refresh your browser.
I was misled as I felt it should have said run the command 'npm run compile' first, then run 'npm watch' and refresh your browser.
There are some changes you need to make if you're using WebPack 3.0+
For webpack.config.js, I had to make the file look like this:
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
app: './src/App.jsx',
vendor:['react', 'react-dom', 'whatwg-fetch', 'babel-polyfill'],
},
output: {
path: path.join(__dirname, './static'),
filename: "[name].bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ["app",'vendor'],
minChunks: Infinity
})
],
module: {
rules:[
{
test:/\.jsx$/,
use: {
loader: 'babel-loader',
query: {
presets: ['react','es2015']
}
}
},
]
},
};
Errors receiving in javascript console:
Warning: Failed context type: The context router.history
is marked as required in LinkContainer
, but its value is undefined
TypeError: undefined is not an object (evaluating 'this.context.router.history.createHref')
I am on windows 10 64 bit machine.
I am not running any vm.
These scripts work
"compile": "babel src --presets react --out-dir static",
"watch": "babel src --presets react --out-dir static -–watch"
These do not work
"compile": "babel src -presets react -out-dir static",
"watch": "babel src -presets react -out-dir static –watch"
I am running npm commands at package.json directory.
npm run compile
npm run watch
The following command in the Using Webpack Manually section is missing the '-o' argument.
$ node_modules/.bin/webpack static/App.js static/app.bundle.js
should be
$ node_modules/.bin/webpack static/App.js -o static/app.bundle.js
forgot to add filter as a parameter to the find method:
db.collection('issues').find(filter).toArray().then((issues) => { ....
Router v4 is a little bit different
HashHistory
import { HashRouter as Router, Route } from 'react-router-dom';
import App from './components/App';
render((
<Router>
<Route exact path="/" component={App} />
</Router> ),
document.getElementById('root'));
BrowserHistory
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './components/App';
render((
<Router>
<Route exact path="/" component={App} />
</Router> ),
document.getElementById('root'));
vagrant@scotchbox:/var/www/public/pro-mern-stack$ node_modules/.bin/babel src --presets react --out-dir static
-bash: node_modules/.bin/babel: Permission denied
It only cares if you have id. If you are missing any other required fields except status it won't notice. When I remove const from the the for loop it works properly.
Thanks for a great book.
Listing 2.6 did not work for me:
"scripts": {
"compile": "babel src –presets react –out-dir static",
"watch": "babel src –presets react –out-dir static –watch",
"test": "echo "Error: no test specified" && exit 1"
},
If I changed it to:
"scripts": {
"compile": "babel src --presets react --out-dir static",
"watch": "babel src --presets react --out-dir static --watch",
"test": "echo "Error: no test specified" && exit 1"
},
Then only I could run compile and watch.
One more thing. One typo on this sentence on the same page:
"Go ahead and run the new command using npm watch."
The right command should be "npm run watch".
Took long time for me to figure out this problems :)
I had issue with Transform until I added a .babelrc in the project folder and in the file I added
{
"presets": ["react"]
}
after the file was added I was able to transform the App.jsx file
When running the code from pro-mern-stack-08-route-query-string using npm run dev-all I get the following error in the console.
[HPM] Error occurred while trying to proxy request /api/issues from localhost:8000 to http://localhost:3000 (ECONNREFUSED)
The URL is : http://localhost:8000/#/issues?_k=c3ajya. I am using node version v6.10.0
when i refresh the edit page ,but i can get nothing.
The book has multiple periods on the return on two functions in the tryMongo.js file:
book has this:
function testWithPromises() {
let db;
MongoClient.connect('mongodb://localhost/playground').then(connection => {
db = connection;
return db.collection('employees').....insertOne({id: 1, name: 'B. Promises'});
it should be
function testWithPromises() {
let db;
MongoClient.connect('mongodb://localhost/playground').then(connection => {
db = connection;
return db.collection('employees').insertOne({id: 1, name: 'B. Promises'});
Also same mistake in Generator function:
book has this:
function testWithGenerator(){
const co = require('co');
co(function*() {
const db = yield MongoClient.connect('mongodb://localhost/playground');
const result = yield db.collection('employees').....insertOne({id: 1, name: 'C. Generator'});
it should be:
function testWithGenerator(){
const co = require('co');
co(function*() {
const db = yield MongoClient.connect('mongodb://localhost/playground');
const result = yield db.collection('employees').insertOne({id: 1, name: 'C. Generator'});
The latest version requires the react-router-dom, which version of react-router-bootstrap should we use to match the version of the react-router component that is used in the book?
I had to use babel-preset-env instead and create a .babelrc file and write
{ "presets": ["env"] }
npm run compile
gives the following error
[email protected] compile C:\pro-mern-stack
babel src –-presets react,es2015 –-out-dir static
–-presets doesn't exist. react,es2015 doesn't exist. –-out-dir doesn't exist
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] compile: `babel src –-presets react,es2015 –-out-dir static`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] compile 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\gf\AppData\Roaming\npm-cache\_logs\2018-05-18T08_19_12_931Z-debug.log
please help
In Webpack 3 output path should be absolute
const path = require('path');
module.exports = {
entry: './src/App.jsx',
output: {
path: path.resolve(__dirname, 'static'),
filename: 'app.bundle.js'
}, module: {
loaders: [{
test: /\.jsx$/,
loader: 'babel-loader'
},]
}
};
In problem #2 for the "Setting State" exercise, it says to look up a guide called Reusable Components in the React Documentation, and to read a section called "No Autobinding". This does not seem to still be in the documentation.
minor: didn't highlight const webpack = require('webpack');
if using webpack 3.0 must use: new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js});
Docs:
https://webpack.js.org/plugins/commons-chunk-plugin/#options
Error message:
Error: Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options
object or the name of the chunk.
Example: if your old code looked like this:
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js')
You would change it to:
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
In ch-6 ,You explained 4 different paradigm for dealing with MongoDb.
I think Es7 async await pattern is the most simple approach.
Babel also provides Es2017 preset.
I think you should include this paradigm in the book and make it default .
The table for the Reports page works fine on port 8000 but not the client port 3000.
I get this on the HMR build:
`
[HMR] Cannot apply update.
[HMR] Error: Module build failed: SyntaxError: Unexpected token, expected } (12:67)
10 |
11 | {props.owner}
12 | {statuses.map((status, index) => ({props.counts{status}}))}
| ^
13 |
14 | );
`
I'm using node 8 and Webpack 3.5.4 with dev-server 2.5.1. I didn't use the object-assign because that was needed for older versions of npm. I'm using 5.3 any suggestions?
On the Network tab I get a pending respond..
In this section you are explaining how a child component would get access to a parents methods.
The way to communicate from the child to a parent is by passing callbacks from the parent to the child, which it can call to achieve specific tasks. In this case, you pass createIssue as a callback property from IssueTable to IssueAdd. From the child, you just call the passed in function in your handler to create a new issue.
You meant IssueList
(parent) to IssueAdd
(child) ?
I would think just by examining the return JSX
from IssueList
...
render() {
return (
<div>
<h1>Issue Tracker</h1>
<IssueFilter />
<hr />
<IssueTable issues={this.state.issues} />
<hr />
<IssueAdd createIssue={this.createIssue} />
</div>
);
}
We could see IssueTable
is sibling to IssueAdd
, no?
The createIssue
prop (I like to think of them as attributes :) ),
<IssueAdd createIssue={this.createIssue} />
is being defined in the handleSubmit function.
handleSubmit(e) {
e.preventDefault();
var form = document.forms.issueAdd;
console.log('form', document.forms);
this.props.createIssue({ . // <-- this bad boy being defined right here
owner: form.owner.value,
title: form.title.value,
status: 'New',
created: new Date()
});
So to sum it up we are passing the function defined in IssueList
so we can use it in IssueAdd
right?
Using webpack manually: testing webpack functionality returns an error:
node_modules/.bin/webpack static/App.js static/app.bundle.js
/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/webpack.js:242
throw err;
^
Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead.
at Object.get [as CommonsChunkPlugin] (/home/mark/pro-mern-stack/node_modules/webpack/lib/webpack.js:165:10)
at Object. (/home/mark/pro-mern-stack/webpack.config.js:14:30)
at Module._compile (/home/mark/pro-mern-stack/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (/home/mark/pro-mern-stack/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at WEBPACK_OPTIONS (/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/convert-argv.js:133:13)
at requireConfig (/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/convert-argv.js:135:6)
at /home/mark/pro-mern-stack/node_modules/webpack-cli/bin/convert-argv.js:142:17
at Array.forEach ()
at module.exports (/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/convert-argv.js:140:15)
at yargs.parse (/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/webpack.js:239:39)
at Object.parse (/home/mark/pro-mern-stack/node_modules/yargs/yargs.js:552:18)
at /home/mark/pro-mern-stack/node_modules/webpack-cli/bin/webpack.js:217:8
at Object. (/home/mark/pro-mern-stack/node_modules/webpack-cli/bin/webpack.js:514:3)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at Object. (/home/mark/pro-mern-stack/node_modules/webpack/bin/webpack.js:80:2)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
I decided to use webpack 3.0 and as such had to rework my webpack.config.js to build the webpack-dev-server successfully. I just use the docs.
my question is: Am I suppose to get a blank page initially?
Here is my config file for reference:
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
app: './src/App.jsx',
vendor:['react', 'react-dom', 'whatwg-fetch'],
},
output: {
path: path.resolve(__dirname, './static'),
filename: "app.bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({name: 'vendor',filename: 'vendor.bundle.js'})
],
module: {
rules:[
{
test:/\.jsx$/,
use: {
loader: 'babel-loader',
options: {
presets: ['react','es2015']
}
}
},
]
},
devServer:{
port: 8000,
contentBase: '/Users/Angel/WebstormProjects/myMern/static',
proxy: {
'/api/*':{
target: 'http://localhost:3000',
}
}
}
};
Thank you.
In Listing 2-6, the command line parameters should have double-dashes rather than single dashes. The repository code is correct, the book has an error.
Correct:
"compile": "babel src --presets react --out-dir static",
"watch": "babel src --presets react --out-dir static --watch",
Incorrect (in the book):
"compile": "babel src -presets react -out-dir static",
"watch": "babel src -presets react -out-dir static -watch",
When using the incorrect script lines, you will get this error in the terminal:
-d doesn't exist. -i doesn't exist. -r doesn't exist. -w doesn't exist. -a doesn't exist. -t doesn't exist. -c doesn't exist. -h doesn't exist
In the webpack.config.js file, I had to use my absolute path when referring to my output file.
I got this error message:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.output.path: The provided value "myMern/static" is not an absolute path!
Thus, ./static didn't work for me I had to write out my whole path. Is this just machine specific?
here is my package.json file:
{
"name": "my-mern-project",
"version": "1.0.0",
"description": "Pro Mern Stack",
"main": "index.js",
"scripts": {
"build": "babel src --presets react --out-dir static",
"compile": "webpack",
"watch": "webpack --watch",
"start": "nodemon -w server server/server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/arrmixer/my-mern-project.git"
},
"keywords": [
"mern"
],
"author": "Angel Rodriguez",
"license": "ISC",
"homepage": "https://github.com/arrmixer/my-mern-project#readme",
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.3",
"mongodb": "^2.2.29"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"nodemon": "^1.11.0",
"webpack": "^3.0.0"
}
}
I'm using webpack 3.0 and babel-loader 7.1.1.
babel src -presets react,env -out-dir static
this has to be corrected to
babel src --presets react,env --out-dir static
It's mentioned properly in the GitHub repo
I installed mongodb via homebrew and I was able to follow the shell examples to work with mongo.
Then in the section 'Reading from MongoDB' I get an error in the server saying: 'TypeError
TypeError: db.collection is not a function'. Anyone know how to fix this?
I even tried changing the line to:
db.collection('issues').find().toArray()
but then it says cannot use find() of undefined.
I checked to see if the database and collection is there and they exist, but just seem to not get the data programmatically.
Use react-router-dom
Also, This will require a complete refresher on routing because the routing has some differences. If in dire need of filler material I found a short video tutorial series free on egghead.io
Error in sending data to server. In console I get the Warning: Each child in an array or iterator should have
a unique "key" prop.
I've changed id to _id in App.jsx, so I'm not sure why I'm getting that warning.
On refresh, the data shows up, but not upon immediate submission.
Is this bc of a mongodb update?
Github code for '03-dynamic-composition` branch is different and more complex compared to what is explained in the book. Is there an errata related for the section?
The first line of the validateIssue function for (const field in issueFieldType) {
should surely be for (const field in issue) {
since otherwise you are just iterating over the fields of the global 'schema' object rather than the issue object. Thus, as it stands, no invalid fields in the issue object will ever be removed.
However, by making this change, the function will now fail to ensure that all required fields are included in the received issue object if a required field is entirely absent from the posted issue object. Thus you actually need two loops, one that iterates over the issue object to check for and prune any unwanted fields and another to iterate over the 'schema' object to check that the issue object contains all the required fields. Something along the lines of:-
function validateIssue(issue) {
// Check for and prune any non-schema fields
// from the issue object.
for (const field in issue) {
if (!issueFieldType[field]) {
delete issue[field];
}
}
// Check that all required fields are present
// in the issue object.
for (const field in issueFieldType) {
const type = issueFieldType[field];
if (type === 'required' && !issue[field]) {
return `${field} is required`;
}
}
if (!validIssueStatus[issue.status]) {
return `${issue.status} is not a valid status`;
}
return null;
}
(My inclination now would be to break this out into three functions)
I've followed to the end of chapter 11. When I run the command "npm run dev-all" and then go to localhost:3000, there's no CSS. It's plain HTML. All the bootstrap classes are still there but bootstrap is not being linked for some reason. Under the sources tab, I see the bootstrap.min.css file and when I click on it, it shows the template with the react elements instead of the bootstrap css file. Here's a link to my git repository https://github.com/edward-hong/pro-mern-stack. How can I get the CSS to look like the way it did before rendering on the server?
In Chapter 10, page 208, just before listing 10-1, since Windows does not support soft links, the book says that the directory node_modules/bootstrap/dist can be copied to the static directory under the project folder. The destination directory should be called bootstrap, this fact is missed out. The text should read thus:
Alternatively, you can copy the entire dist
directory under the Bootstrap library
into the static
directory, and rename the copied directory as bootstrap
.
The following command results in an error:
C:\Marc\Web Development\MERN\chapter_02>node_modules.bin\babel src --presets react --out-dir static
src doesn't exist
This is my webpack.server-config.js file for Webpack 3:
const webpack = require('webpack');
const path = require('path');
module.exports = {
target: 'node',
entry: ['./server/index.js', './node_modules/webpack/hot/poll?1000'],
output: {
path: path.join(__dirname, './dist'),
filename: 'server.bundle.js',
libraryTarget: 'commonjs',
},
resolve: {
extensions: [' ', '.js', '.jsx'],
},
externals: [/^[a-z]/],
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
},
},
}, {
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['es2015-node'],
},
},
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devtool: 'source-map',
};
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.