DEV Community

Cover image for API REST - typeScript, nodejs, express
Reynaldo Quispe Soca
Reynaldo Quispe Soca

Posted on

3 1

API REST - typeScript, nodejs, express

  • Crear al package.json

    npm init -y

  • Instalar typescript

    npm i typescript -D

  • instalar compilador TS

    npx tsc --init

  • configurar tsconfig.json

    descomentar estas lineas

    "baseUrl": "./src",  
    "outDir": "./build",
    "allowSyntheticDefaultImports": true, 
    
  • Creamos nuestra carpeta src
    dentro de esa carpeta creamos el index.ts y de ejemplo creamos una función suma.

    const add = (a:number,b:number)=>{
        return a+b;
    }
    
    console.log(add(2,3));
    
  • Ejecutamos el programa
    npx tsc src/index.ts

  • Agregando script para ejecutar en el archivo package.json

     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1",
       "start": "tsc src/index.ts"
     },
    
  • Ahora solo ejecutamos
    npm start

  • instalamos ts-node
    npm i ts-node

  • instalamos express y sus tipos
    npm i express
    npm i --save-dev @types/express

  • instalamos para que el servidor actualize solo
    npm i ts-node-dev

  • cambiando la configuración en el archivo package.json

     "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "ts-node-dev src/index.ts"
     },
    
  • Creando el servidor en el archivo index.ts

    import express, { Request, Response } from 'express';
    
    const app=express();
    
    app.get('/', (req:Request, res:Response)=>{
        res.status(200).send('Hola este es mi server')
    });
    
    app.listen(3000, ()=>console.log('Server started'));
    

    RESULTADO:
    Image description

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️