Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 24, 2022 10:08 pm GMT

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 funcin 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 configuracin 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


Original Link: https://dev.to/reynaldoz/api-rest-typescript-nodejs-express-125b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To