Giter VIP home page Giter VIP logo

project-10-bank-api's Introduction

Project #10 - Argent Bank API

This codebase contains the code needed to run the backend for Argent Bank.

Getting Started

Prerequisites

Argent Bank uses the following tech stack:

Please make sure you have the right versions and download both packages. You can verify this by using the following commands in your terminal:

# Check Node.js version
node --version

# Check Mongo version
mongo --version

Instructions

  1. Fork this repo
  2. Clone the repo onto your computer
  3. Open a terminal window in the cloned project
  4. Run the following commands:
# Install dependencies
npm install

# Start local dev server
npm run dev:server

# Populate database with two users
npm run populate-db

Your server should now be running at http://locahost:3001 and you will now have two users in your MongoDB database!

Populated Database Data

Once you run the populate-db script, you should have two users in your database:

Tony Stark

Steve Rogers

API Documentation

To learn more about how the API works, once you have started your local environment, you can visit: http://localhost:3001/api-docs

Design Assets

Static HTML and CSS has been created for most of the site and is located in: /designs.

For some of the dynamic features, like toggling user editing, there is a mock-up for it in /designs/wireframes/edit-user-name.png.

And for the API model that you will be proposing for transactitons, the wireframe can be found in /designs/wireframes/transactions.png.

project-10-bank-api's People

Contributors

bencodezen avatar hayvthom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

project-10-bank-api's Issues

Back-End qui crash : Error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

Impossible de lancer le back-end qui plante apres quelques secondes d'execution avec l'erreur suivante qui remonte dans la console :

⚡ npm run dev:server

[email protected] dev:server
nodemon ./server/server.js

[nodemon] 2.0.22
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node ./server/server.js
Server listening on http://localhost:3001
Database Connectivity Error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
/Users/julien/Travail/UDEMY/React-Projects/Project-10-Bank-API-master/server/database/connection.js:14
throw new Error(error);
^

Error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at module.exports (/Users/julien/Travail/UDEMY/React-Projects/Project-10-Bank-API-master/server/database/connection.js:14:11)

Node.js v21.7.2
[nodemon] app crashed - waiting for file changes before starting...

Environnement :

  • Node : version v21.7.2
  • MangoDB : version v7.0.2

**J'ai essayer de faire les modifications suivantes : **
1 - fichier server/databese/connection.js suivante (remplacement de localhost par l'adresse 127.0.0.1):

const databaseUrl =
process.env.DATABASE_URL || "mongodb://127.0.0.1/argentBankDB";

2- fichier /.env (remplacement de localhost par l'adresse 127.0.0.1)
DATABASE_URL="mongodb://127.0.0.1/argentBankDB"

Une solution ??

Merci d'avance

The Swagger API documentation has a slight issue when making a POST/PUT request to the API with a JWT

So the documentation has a slight issue when making POST or PUT requests

When making a POST or PUT request, we must input a string with the keyword “Bearer” and then the JSON Web Token, like this:

"Bearer [JWT]"

Though there's a problem, for some unknown reason, when making the POST/PUT request,

Curl adds another double-quote at the end of the Authorization string value, making the token invalid:

image

So the developer has to remove the last double quote at the end of the JWT, so we end having to input the token like this:

"Bearer [JWT]

for the POST request to work properly

How to reproduce this error yourself

  1. Start the Back-End server and go to the Swagger API doc. with this address: http://localhost:3001/api-docs/#/

  2. Go to the User Module → POST - /user/login/ → add the “[email protected]” to the email and “password123” for the password:
    image

  3. Click “execute” and copy the JWT without the double quotes:
    image

  4. Go to POST - /user/profile/ → Input your JWT like this:

"Bearer [JWT]"

Example:
image

(NB: I changed the width of the input in CSS to make the entire JWT visible)

  1. Click the “Execute” button, and you'll see an error message that the token is invalid:
    image

Install API on macOS

Do you struggle to install the API on macOS ?

If you have the error [nodemon] app crash... you probably didn't install MongoDB Community Edition.
And don't worry if the mongo --version is not working....

What I did to fix the error:

  1. Follow this link for complete instructions https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/
  2. If you don't have home brew package manager installed (global) then: https://brew.sh/index_fr

So once brew is installed, in your macOS terminal: you can run:

  1. brew tap mongodb/brew

  2. brew install [email protected]

⚠️ like me, you can have this error:

image

If you had it just follow the img instructions (so install xcode-select) and then launch again brew install [email protected]

  1. now you can check the install with mongod --version

  2. and then run mongodb community with brew services start [email protected]

(to stop it : brew services stop [email protected])

Now, you can clone the repo and:

  1. npm i
  2. add MongoDB NodeJS Driver npm install mongodb --save
  3. Start your local server npm run dev:server
  4. Get the populate database npm run populate-db

✨ Your Api should be ready 😃

👉 http://localhost:3001/api-docs/

Hope it helps ! 👋

npm run populate-db renvoi: Error: connect ECONNREFUSED 127.0.0.1:3001

Est-ce normal que lorsqu'on exécute la commande npm run populate-db la réponse renvoyé est :

Error: connect ECONNREFUSED 127.0.0.1:3001
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3001,
  config: {
    url: 'http://localhost:3001/api/v1/user/signup',
    method: 'post',
    data: '{"firstName":"Tony","lastName":"Stark","email":"[email protected]","password":"password123"}',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json;charset=utf-8',
      'User-Agent': 'axios/0.19.2',
      'Content-Length': 89
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    validateStatus: [Function: validateStatus]
  },
  request: Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: true,
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      protocol: 'http:',
      maxRedirects: 21,
      maxBodyLength: 10485760,
      path: '/api/v1/user/signup',
      method: 'POST',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: 'localhost',
      port: '3001',
      nativeProtocols: [Object],
      pathname: '/api/v1/user/signup'
    },
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 89,
    _requestBodyBuffers: [ [Object] ],
    _onNativeResponse: [Function],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: true,
      socket: [Socket],
      connection: [Socket],
      _header: 'POST /api/v1/user/signup HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json;charset=utf-8\r\n' +
        'User-Agent: axios/0.19.2\r\n' +
        'Content-Length: 89\r\n' +
        'Host: localhost:3001\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      insecureHTTPParser: undefined,
      path: '/api/v1/user/signup',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'http://localhost:3001/api/v1/user/signup',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function]
}

Impossibilité de lancer le backend

ISSUS 1 :

désinstaller mongo et réinstaller une version antérieur a la version 6 (5.0.23)


ISSUS 2:

  • modifier dans le fichier .env "localhost" par "127.0.0.1"
  • modifier également dans "server/database/connection.js" par :
const databaseUrl =
  process.env.DATABASE_URL || 'mongodb://127.0.0.1/argentBankDB'

[tips] : Install the project with docker

Here is a simple way how to install the project using docker :

Step 1
in the connection.js file, add the property : useUnifiedTopology: true to the url connection :

await mongoose.connect(databaseUrl, { useNewUrlParser: true, useUnifiedTopology: true })

Step 2
At the root level of the project, create a DockerFile :

# Use the official Node.js 12 image as base image
FROM node:12
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD ["npm", "run", "server"]

Step 3
At the root level of the project, create a docker-compose.yml

version: '3'

services:
  # Node.js application service
  app:
    build:
      context: .
    ports:
      - "3001:3001"
    depends_on:
      - mongo
    environment:
      DATABASE_URL: "mongodb://mongo/argentBankDB"  # Use the service name 'mongo' as the hostname

  # MongoDB service
  mongo:
    image: mongo
    user: '502:502'
    ports:
      - "27017:27017"
    volumes:
      - ./data:/data/db:rw

volumes:
  mongo:
    external: true

The line user: '502:502 is needed to give you the right to copy the data folder from your container in your local machine.
You probably need to change the ID by your own id (on mac os you can get it by running : id -u in a terminal)
`Step 4

run docker-compose up

Capture d’écran 2024-01-18 à 23 18 08

Step 5
At this step your project is running (api + mongodb).
Now you need to populate the database. Here is how you can do :

  • Get your container ID by running docker container ls
  • Run the following command : docker exec -it 00460714d1d9 bash
  • Then you can just run the command npm run populate-db

yarn dev:server renvoi cette erreur , j'ai reinstallé plusieurs fois mongodb, j'ai bien verifié que mongo et ses services tournent sur ma machine, mais j'ai toujours cette erreur

$ yarn dev:server
yarn run v1.22.19
warning ......\package.json: No license field
$ nodemon ./server/server.js
[nodemon] 2.0.22
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node ./server/server.js
Server listening on http://localhost:3001
Database Connectivity Error: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
C:\Users\anis\Desktop\OpenClassRooms\Project-10-Bank-API\server\database\connection.js:10
throw new Error(error);
^

Error: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at module.exports (C:\Users\anis\Desktop\OpenClassRooms\Project-10-Bank-API\server\database\connection.js:10:11)

Node.js v18.16.1
[nodemon] app crashed - waiting for file changes before starting...

Resume Project-10-Bank-API

Dans les explications de la mise en place du projet,
il n'est pas indiqué quelle version de Node et Mongo, il faut installer, car certaines mises à jour peuvent bloquer la mise en place du server.

De plus, vous indiquez qu'il est possible de vérifier que le server marche si on va sur le lien suivant :
http://locahost:3001/ mais il ne marche pas parce qu'il manque le "l" donc si personne ne fait attention ou qu'il ne le tape pas d'eux même, ils peuvent se retrouver dans un problème qu'y n'est pas.

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.