Skip to content

Instantly share code, notes, and snippets.

@basir
Last active January 19, 2023 18:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save basir/d121df24c47861e13a1cdcbed1cca902 to your computer and use it in GitHub Desktop.
Save basir/d121df24c47861e13a1cdcbed1cca902 to your computer and use it in GitHub Desktop.

Amazona FAQ

If you can not find you question, put it as comment below. I will answer it and add it to the list.

Home Screen

TypeError: Cannot read property 'map' of undefined HomeScreen

It means that products is null. check the value of products when loading = true, It should be empty array [] Also, check the value of products when loading = false, It should be products array. If you are using redux, make sure that in the reducer you set the default value for products to an empty array.

function productListReducer(state = { products: [] }, action) {
...
}

Also in ProductScreen.js make sure you are checking loading === false && error === false when rendering products, otherwise you will get this error.

Cannot use import statement outside of a module

You did not set babel correctly to transpile ES6 code to ES5. Follow this:

  1. npm install @babel/core, cli, node, preset-env
  2. Create .babelrc
{ presets: [[“@babel/preset-env”]]}
  1. Edit package.json
{
scripts:{
"start":"nodemon –exec babel-node server.js"
}

Localhost:3000/api/products 404 Error

You did not create res.get("/api/products") on server.js or you did not set proxy. check below for proxy setting.

Proxy error: could not proxy request /api/products

Check this:

  1. frontend/package.json
{
  "name": "frontend",
  "proxy": "http://127.0.0.1:5000",
...
}
  1. stop running frontend and backend
  2. Run backend first
npm start
  1. Then frontend
cd frontend
npm start

How to dynamically add categories in sidebar

You need to create an api for it. add this to productRoutes.js

router.get('/categories', asyncHandler(async (req, res) => {
  const categories = await Product.find().distinct('category');
  res.send(categories);
}));

Product Screen

Type Error: Can not read property name of undefined

const product = products.find(x => x._id = props.math.params.id);

it means that either products array is empty or the param id does not exist in the array. after find method check product is not null then render it.

Cart Screen

After logout cart still shows orders.

Edit userActions.js as follow:

const logout = () => (dispatch) => {
  Cookie.remove("userInfo");
 Cookie.remove("cartItems");
  dispatch({ type: USER_LOGOUT })
}

Invalid Token on click Place order buton

re-login. it fixes the error if you had a successful login before. it is because the token expires in 48h. you can change it in utils.js

Profile Screen

Cast to ObjectId failed for value "mine" at path "_id" for model "Order"

Move router.get("/mine") before router.get("/:id") in orderRoutes.js

Manage Products

Cannot read property 'token' of undefined

Make sure in frontend you supply token in ajax request

Authorization: `Bearer ${token}`

Also in backend utils.js you implemented isAuth and isAdmin like course source code and in the productRoute.js you have this order:

router.post("/", isAuth, isAdmin, (req, res) => {

MongoDB

ServerDescription { address: 'localhost:27017' error: [MongoNetworkError]

You didn't install mongodb. Install it from here

Cannot load my localhost:5000/api/users/createadmin

You didn't install mongodb. Install it from here

E11000 duplicate key error collection: amazona.users index: email_1 dup key

You need to change the email in userRoutes.js method createAdmin to create a new admin.

Paypal

Not login to Paypal account

sandbox.paypal.com is a copy of paypal.com but you can only login here with sandbox accounts you created on the developer portal. More info here

Deploy

Error git add: you have another repo inside current repo

go to the frontend folder and delete the .git folder inside that. it should work.

Error in “rm -rf dist && babel backend -d dist”

In windows use this:

rm -rf` with `rmdir /s /q

why did you use eslint?

because it applies coding rules which your code consistent and elegant.

Error: ENOENT: no such file or directory, stat '\frontend\build\index.html'

you need to run

npm run build

then it works.

Heroku deploy steps

  1. Create git repository
$ git init
  1. Create Heroku Account and install Heroku CLI
  2. Login on terminal and create app
$ heroku login
$ heroku apps:create amazonaapp
  1. Edit package.json
script: {
 "build": "rm -rf dist && babel backend -d dist",
 "heroku-postbuild": "npm run build && cd frontend && npm install && npm run build"
 },
"engines": { "node": "12.4.0", "npm": "6.9.0"}
  1. Create Procfile
web: node dist/server.js
  1. Set Cloud MongoDB connection string
$ heroku config:set MONGODB_URL=<cloud mongodb connection string>
  1. Edit config.js
PORT: process.env.PORT || 5000
  1. Edit server.js
app.use(express.static(path.join(__dirname, '/../frontend/build')));
app.get('*', (req, res) => res.sendFile(path.join('${__dirname}/../frontend/build/index.html'));
app.listen(config.PORT, …)
  1. Edit .babelrc
[
  "@babel/preset-env",
  {"targets": {"node": "current"}}
]
  1. Commit and push
$ git add . && git commit -m "publish"
$ git push heroku

Create Cloud MongoDB

  1. Create Cloud MongoDB Account
  2. Open cloud.dashboard.com
  3. Left sidebar -> Select Security -> Database Access
  4. Select Add New User button
  5. Enter user name and password and click Add User
  6. Left sidebar > Select Security > Network Access
  7. Select Add IP Address
  8. Enter 0.0.0.0/0 in Whitelist Entry and click Confirm
  9. Left sidebar > Cluster > collections
  10. Create new database, set database name and collection name
  11. Get connection string
  12. Left sidebar > Select Altas > Cluster
  13. Click Connect
  14. Click Connect to your application
  15. Click Copy button
  16. Paste it in your text editor
  17. Replace and with step 5, and with step 10
  18. Use it connection string to publish on heroku (step 6)

ReferenceError: regeneratorRuntime is not defined!

Follow Heroku deploy steps to fix this error.

ERR! build: rmdir /s /q dist && babel backend -d dist

Change your command in package.json to

"scripts": {
 "build": "rm -rf dist && babel backend -d dist",
 ...

How to run project locally

If it does not work you can simply clone the course repo:

https://github.com/basir/node-react-ecommerce

Then follow this guide to run it locally:

https://github.com/basir/node-react-ecommerce#run-locally

Then compare your code with this.

Subtotal ( NaN items) : NaN

  1. clean your cookie
  2. cast selected value in select box for QTY to number. use this: Number(e.traget.value)
  3. Test it again

PORT IN USE 5000

to fix this issue you need to close all instances of nodejs in process manager in your os. then restart VS Code and it should be fixed.

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

You didn't install and run MongoDB correctly. Install it from https://docs.mongodb.com/manual/administration/install-community/

@shumkar-barpiev
Copy link

How we can connect backend(data.js) with frontend(e. g. src\screens\ProductScreen.js)? Because when I delete this lines:
import data from '../data';
...
const product = data.products.find(x=>parseInt(x._id) === parseInt(props.match.params.id))
console.log(props.match.params.image);

from ProductScreen.js,
gives an error message like this : Line 31:29: 'product' is not defined no-undef

@lokesh-acharya
Copy link

Getting MODULE_NOT_FOUND in heroku after successful deployment.
Error: Cannot find module '/app/dist/server.js'

@orliyahTheCoder
Copy link

I am receiving a GET http://localhost:3000/api/product/1 404 (Not Found) error and a ProductScreen.js:66 Uncaught (in promise) Axios error. I have looked at all my code and tried to compare it with the GitHub code and I am still receiving the error. The video I was watching was 'Improving Add To Cart'. Please help me. What could I be doing wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment