I am monitoring a port, yet the server is still not up and running

This morning everything was working perfectly, but after restarting my computer, it's not running anymore.

I'm at a loss on how to fix this issue.

[nodemon] starting ts-node src/index.ts

[nodemon] clean exit - waiting for changes before restart

Index.ts

import "dotenv/config";
import "reflect-metadata";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import { UserResolvers } from "./UserResolvers";
import { createConnection } from "typeorm";
import cookieParser from "cookie-parser";
import { verify } from "jsonwebtoken";
import cors from "cors";
import { User } from "./entity/User";
import { sendRefreshToken } from "./sendRefreshToken";
import { createAccessToken, createRefreshToken } from "./auth";

(async () => {
  const app = express();
  app.use(
    cors({
      origin: "http://localhost:3000",
      credentials: true,
    })
  );
  app.use(cookieParser());
  app.get("/", (_req, res) => res.send("hello"));
  app.post("/refresh_token", async (req, res) => {
    const token = req.cookies.jid;
    if (!token) {
      return res.send({ ok: false, accessToken: "" });
    }

    let payload: any = null;
    try {
      payload = verify(token, process.env.REFRESH_TOKEN_SECRET!);
    } catch (err) {
      console.log(err);
      return res.send({ ok: false, accessToken: "" });
    }

    // token is valid and
    // we can send back an access token
    const user = await User.findOne({ uid: payload.userId }.uid);

    if (!user) {
      return res.send({ ok: false, accessToken: "" });
    }

    if (user.tokenVersion !== payload.tokenVersion) {
      return res.send({ ok: false, accessToken: "" });
    }

    sendRefreshToken(res, createRefreshToken(user));

    return res.send({ ok: true, accessToken: createAccessToken(user) });
  });

  await createConnection();

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [UserResolvers],
    }),
    context: ({ req, res }) => ({ req, res }),
  });

  apolloServer.applyMiddleware({ app, cors: false });

  app.listen(4000, () => {
    console.log("express server started");
  });
})();

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "."
},
"include": ["src/**/*.ts"],
   "exclude": ["node_modules", "**/*.spec.ts"]
}

package.json

{
  "name": "auth-server",
  "version": "0.0.1",
   "description": "Awesome project developed with TypeORM.",
  "dependencies": {
     "apollo-server-express": "^3.10.2",
     "bcryptjs": "^2.4.3",
     "cookie-parser": "^1.4.4",
     "cors": "^2.8.5",
     "express": "^4.18.1",
     "express-session": "^1.16.1",
     "graphql": "^14.2.1",
     "jsonwebtoken": "^8.5.1",
     "pg": "^7.10.0",
     "reflect-metadata": "^0.1.13",
     "ts-node": "^10.9.1",
     "type-graphql": "^1.1.1",
     "typeorm": "0.2.16",
     "typescript": "^4.8.3"
   },
   "devDependencies": {
      "@types/bcryptjs": "^2.4.2",
      "@types/cookie-parser": "^1.4.1",
      "@types/express": "^4.16.1",
      "@types/express-session": "^1.15.12",
      "@types/graphql": "^14.2.0",
      "@types/jsonwebtoken": "^8.3.2",
      "@types/node": "^11.13.8",
      "ts-node-dev": "^1.0.0-pre.32"
   },
  "scripts": {
      "dev": "nodemon --exec ts-node src/index.ts",
      "typeorm": "typeorm-ts-node-commonjs"
   }
 }

Answer №1

To execute the script, consider running the following command npx ts-node ./src/index.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access the uploaded file as a stream through Express

I'm currently working on an API that includes a function to upload files to another website, acting as a proxy for the file upload process through the API. The destination website requires specific steps to be followed (such as sending the destinatio ...

Tips for handling a local Mongo Database on an Android device

My goal is to develop an Android app that can function completely offline, allowing users to add new entries, view existing ones, delete and edit them without requiring internet access. For the backend, I plan to use nodejs with express and MongoDB. While ...

Here is a way to retrieve and display the variable value within the res.json method: {message:}

How can I include the value of orderId in the message section of res.json() instead of getting it as a string after the $ symbol? if(order.length > 0) { res.status(200).json(order); } else{ res.json({messag ...

What is the best way to set up an endpoint in Angular for image uploading?

Using the Kolkov Angular editor in my Angular application, I have successfully created a rich text editor. Currently, I am looking to upload images from the editor to the server. I already have a function in place that takes a file as an argument and send ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

Updating Angular 2 template based on specific conditions of model values

I want to update a view only when the total votes reach a number that is a multiple of ten. I am incrementing a random element in an array called rows every 10 milliseconds, ultimately adding up to the total number of votes. Is there a simple way in angula ...

Interactive text animations using PIXI.js and state management with Redux

In my game class, I created an element: private winAmountText: PIXI.Text = new PIXI.Text('0') Within the constructor, I have the following code: this.winAmountText.style = new PIXI.TextStyle({ fill: 0xFFFFFF, fontSize: 86 }) this.setWinA ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

The Nest dependency resolution is experiencing difficulties

Having trouble identifying the issue with my code. Upon reviewing the error message, everything seems fine. When running npm start in the console, the following error appears: Nest can't resolve dependencies of the DescribeService (UrlsAfipServi ...

What is the process for running an Express JS project on a secure shell?

1. Can you provide a detailed explanation of how to set up a secure shell in an Express project? var express = require('express'); var app = express(); var pg = require('pg'); app.listen(7207); var bodyParser = require('body-pars ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

Semantics error in the EJS template due to a misplaced semicolon within a switch

I attempted to change the condition inside the EJS template but encountered an error Here is my code : <% switch(check) {%> <% case check == 'like' : %> <button href="#<%=item._id%>" id="like" ...

Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests. I want to implement error handling by using the Ha ...

Prevent auth0 express middleware from causing server crashes by handling failures silently

I am currently integrating auth0 into a node project for authentication using JWTs. Each request to an authenticated endpoint requires a token, and auth0 provided me with this middleware function: import {auth} from 'express-oauth2-jwt-bearer'; i ...

Implementing dynamic display of div based on dropdown selection in typescript

A solution is needed to display or hide specific div elements based on a dropdown selection using Typescript. Sample HTML file: <select class="browser-default custom-select"> <option selected>single</option> <option value="1"> ...

Troubleshooting: Express router does not correctly implement Mongoose's findByID method when using URL route

After following a tutorial, I encountered an issue with the code: /* GET one item. */ router.get('/items/:id', (req, res) => { Item.findById(req.param.id, (err, items) => { if (err) res.status(500).send(error) res.status(200).js ...

When using Mongoose populate, it sometimes returns an array of objects instead of the actual data from the field

There is a query that fetches the availability array from the parking model based on the parking Id in the booking model. The query used is as follows: let startTime = await Booking.findOne( { bookingId: req.params.id }, { startTime: 1, _id: 0 ...

Creating a Typescript interface with at least one specified type

I've recently delved into using typescript. Currently, I'm faced with a scenario where I need to import available types from backend endpoints. In one specific instance, an endpoint can support two types as parameters. Example: interface B ext ...