Git Product home page Git Product logo

node-express-course's Introduction

node-express-course's People

Contributors

john-smilga avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-express-course's Issues

Tasks not showing on the browser

So after doing all the server-side codes and connecting it to the public file so I could see the list of my tasks on the browser, i noticed I was getting an error.
After debugging turns out the error was coming from here, "line number 11"
image

So the issue was we were trying to destructure tasks from the returned data, instead of renaming data to tasks,

const {data: {tasks}} = axios.get('api/v1/tasks') this is throws an error

const {data: tasks} = axios.get('api/v1/tasks') this works fine

server.listen not allowing settimeout to work

I am going through @john-smilga Nods-JS Course , and currently I am on module 'http'.
Below is a simple code which I wrote :-

var http = require('http');
var server = http.createServer(function (req,res) {
  res.end("Hello World") 
})

server.listen(5000);



setTimeout(() => {server.close() } ,4000);   // put anytime duration here 

The behaviour which I expected was that server should stay on for 4 seconds and then closes. But rather what is happening is that server stays on indefinitely and we can do anything, however when we leave server idle for 4 seconds, after that if we reload or do anything then the timer of 4 seconds starts and after that server closes.
Means from 0 to N seconds I kept on working, then left idle for 4 seconds, on 24th second I reloaded again and then on 29th second the server is closing.

Why is it happening like that. Basically settimeout will move to call queue after 5 seconds and then it should be moved to call stack by event loop and close the server as soon as it goes idle.We can put anytime duration in timeout we have to wait leave server idle for that duration for the settimeout to begin and after that 5 seconds it take to close it.
Why is it behaving so ?

module express not found

os win10
task manager
Process exited with code 1
C:\Program Files\nodejs\node.exe .\03-task-manager\final\app.js
Uncaught Error: Cannot find module 'express'

Spelling in Readme file

Course Exclusive
Node Tutorial and Projects Course

File Upload (local and cloudinary)
Send Email (nodemailer,ethereal and sendgrid )
Stripe Payment
E-Commerce API
Auth Workflow (verify email, reset password)

### Sessons to Sessions
`Yelp Clone

04-STORE-API: page functionality is not working

In post-man, when I set page =1, I get this response:

image

Now, when I set page = 2, I get the same response:

image

I am supposed to get different responses for different values of page, but I am getting the same response.
Where did I go wrong?

This is controllers/product.js :

const Product = require("../models/product")
const productsList = require("../products.json")

const getAllProductsStatic = async (req, res) => {
    const search = "a"
    const products = await Product
                            .find({ 
                                featured: false, 
                                name: { $regex: search, $options: "i" } //name: "vase table"
                            })
                            .sort("name -price")
                            .select("name price")
                            .limit(5)
                            .skip(2)
    res.status(200).json({ msg: products, numOfProducts: products.length })
}

const getAllProducts = async (req, res) => {
    console.log(req.query) 

    const { featured, company, name, sort, fields } = req.query
    const queryObject = {}

    if (featured) {
        queryObject.featured = featured === "true" ? true : false
    }

    if (company) {
        if (company == "ikea" || company == "liddy" || company == "marcos" || company == "caressa") {
            queryObject.company = company
        }
        else {
            return res.status(404).json({ msg: "this company doesn't exist")
        }
    }

    if (name) {
        queryObject.name = {
            $regex: name,
            $options: "i"
        }
    }

    let result = Product.find(queryObject)

    if (sort) {
        const sortList = sort.split(",").join(' ') //console.log(sortList) 
        result = result.sort(sortList)
    }
    else {
        result = result.sort("createdAt") 
    }

    // FIELDS
    if (fields) {
        const fieldsList = fields.split(",").join(" ")
        result = result.select(fieldsList)
    }

    const page = Number(req.query.page) || 1  
    const limit = Number(req.query.limit) || 10
    const skip = (page -1) * limit 
    result = result.skip(skip).limit(limit) 

    const products = await result

    res.status(200).json({ msg: products, numOfProducts: products.length })
}

module.exports = { getAllProducts, getAllProductsStatic }

asyncWrapper throwing error.

const asyncWrapper = (fn) => {
  return async (req, res, next) => {
    try {
      await fn(req, res, next);
    } catch (error) {
      next(error);
    }
  };
};

module.exports = asyncWrapper;

Its crashing app. In controller\taskController.js:6

const getAllTasks = asyncWrapper(async (req, res) => {
                    ^

TypeError: asyncWrapper is not a function
    at Object.<anonymous> (D:\Workplace\iotStack\w02\controller\taskController.js:6:21)
←[90m    at Module._compile (internal/modules/cjs/loader.js:956:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:812:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:724:14)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:849:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:74:18)←[39m
    at Object.<anonymous> (D:\Workplace\iotStack\w02\routes\tasks.js:11:9)
←[90m    at Module._compile (internal/modules/cjs/loader.js:956:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)←[39m
[nodemon] app crashed - waiting for file changes before starting...

Removal of mongoose.connect() options for Mongoose 6.x

Description

On migrating/using Mongoose 6.x, one may get deprecating warning options due to usage of following options when connecting to the database through mongoose.connect(): useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex.

Files

To Reproduce

Install the npm package for Mongoose 6.x. Implement connect.js as in the final folder, with options.

Fix

As per https://mongoosejs.com/docs/migrating_to_6.html: useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.
The options need to be removed from the code, to resolve the issue.

E-Commerce API - Issue with deprecation `remove` to `deleteOne` instead

Prerequisites

  • [x ] I have written a descriptive issue title

Mongoose version
^8.5.3

Node.js version
20.x

Operating system
Linux

Operating system version (i.e. 24.04, 11.3, 10)
Linux 6.8.7-arch1-

Issue
I am currently in the E-commerce API module, and specifically in the remove all reviews and Aggregation pipeline setup. The current version I am using, remove() is deprecated. And this is How I dealt with remove all reviews:

remove all reviews:
Product js
productController js (1)

Aggregation pipeline in order to trigger the remove hook with deleteOne:
reviewController js
Review js

Add social banner

I had created a article of "Top 10 trending github repos of the week🐮."

Here https://dev.to/ksengine/top-10-trending-github-repos-of-the-week-1mk8

I can't see your social banner there.
Please add a social banner to this project

According to github docs

Customizing your repository's social media preview
You can customize the image displayed on social media platforms when someone links to your repository.

Until you add an image, repository links expand to show basic information about the repository and the owner's avatar. Adding an image to your repository can help identify your project across various social platforms.

See https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/customizing-your-repositorys-social-media-preview

Thanks 😊

Usage of `switch` statement to eliminate repeated `if` statements in the `error-handler.js` file

Instead of having so many repetitive if statements. switch statements can be used instead. I also added the { StatusCode } to make it more readable.

  switch (true) {
    case err.code && err.code === 11000:
      customError.msg = `Duplicate value entered for ${Object.keys(err.keyValue)} field, please choose another value`;
      customError.statusCode = StatusCodes.BAD_REQUEST;
      break;
    case err.name === 'ValidationError':
      customError.msg = Object.values(err.errors).map((item) => item.message).join(',');
      customError.statusCode = StatusCodes.BAD_REQUEST
      break;
    case err.name === 'CastError':
      customError.msg = `not item found with id: ${err.value}`;
      customError.statusCode = StatusCodes.NOT_FOUND; 
  }

10-e-commerce-api uploadImage doesn't work.

Multipart/forms with file uploads can be tricky. Here's a snippet of code from the productController.js I used to get it working. Cloudinary was used in 07-file-upload so maybe it didn't have the problem that 10-e-commerce has.

const uploadImage = async (req, res) => {
if (!req.files) {
throw new CustomError.BadRequestError('No File Uploaded');
}

//  const productImage = req.files.image;
const uploadProperties = Object(Object.entries(req.files)[0][1])

if (!uploadProperties.mimetype.startsWith('image')) {
  throw new CustomError.BadRequestError('Please Upload Image');
}

const maxSize = 1024 * 1024;
if (uploadProperties.size > maxSize) {
  throw new CustomError.BadRequestError(
   'Please upload image smaller than 1MB' );
}

const imagePath = path.join(
__dirname,
'../public/uploads/' + ${uploadProperties.name}
);

await uploadProperties.mv(imagePath);
res.status(StatusCodes.OK).json({ image: /uploads/${uploadProperties.name} });
};

next(error) skipping middlewares

In the project of task-manager , this is the source-code in middleware/async.js

const asyncWrapper = (fn) => {
  return async (req, res, next) => {
    try {
      await fn(req, res, next)
    } catch (error) {
      next(error)              // Line ABC
    }
  }
}

module.exports = asyncWrapper

And this is the code in app.js

const express = require('express');
const app = express();
const tasks = require('./routes/tasks');
const connectDB = require('./db/connect');
require('dotenv').config();
const notFound = require('./middleware/not-found');
const errorHandlerMiddleware = require('./middleware/error-handler');

// middleware

app.use(express.static('./public'));
app.use(express.json());

// routes

app.use('/api/v1/tasks', tasks);

app.use(notFound);
app.use(errorHandlerMiddleware);
const port = process.env.PORT || 5000;

const start = async () => {
  try {
    await connectDB(process.env.MONGO_URI);
    app.listen(port, () =>
      console.log(`Server is listening on port ${port}...`)
    );
  } catch (error) {
    console.log(error);
  }
};

start();


Now the line ABC deom async.js shall execute app.use(notFound) , but instead it executes app.use(errorHandlerMiddleWare). Why is it so ?

Overwrite:true not working

At 02:25 , overwrite:true was written as option in PUT request and to implement it default:false was removed from Schema.js.However as of now in March 2023 , I can see that overwrite:true is no more working even if changing schema. I think something has changed.
Anyone having any idea ?

TypeError: result.skip is not a function

const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
const skip = (page - 1) * limit;

result = result.skip(skip).limit(limit);

//error in terminal
TypeError: result.skip is not a function

1-block-js section: does not work

hi,

I got this error following the tutorial at the 1-block-js section.

node:events:505
throw er; // Unhandled 'error' event
^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:372:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server. (my path)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}

06.5 JOBSTER-API: showStats - ISSUE Node: 20.x - Mongoose version "mongoose": "^8.5.2"

In the controller/jobs.js -> showStats
When I try this code from the course it is not working for the new Mongoose version "mongoose": "^8.5.2":

const showStats = async (req, res) => {
  let stats = await Job.aggregate([
    { $match: { createdBy: new mongoose.Types.ObjectId(req.user.userId) } },
    { $group: { _id: '$status', count: { $sum: 1 } } },
  ])
  console.log(stats)
  res.status(StatusCodes.OK).json({ defaultStats: {}, monthlyApplications: [] })
}

This is the issue from my console:

issueJobs

When you try the suggestion using the new it will work but there will be some deprecation warnings:
codeIssue

To solve the issue what I did is to use the string interpolation to make sure that I am passing a string.

fixed

Of course, if you're not using the new version of Node and Mongoose, this might not work for you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.