TypeScript小白初體驗之前後端交互

前提:有TS環境配置,有運行VSCode基本經歷;

  1. 環境配置:打開任意新文件夾,新建文件:tsconfig.json用於ts配置,內容包括:
    {
        "compilerOptions":{
            "module": "commonjs",
            "sourceMap": true,
            "outDir": "dist",
            "declaration": true,
            "experimentalDecorators": true,
            "removeComments": false,
            "noImplicitAny": true,
            "preserveConstEnums": true,
            "target": "es2018"
        },
        "exclude": [
            "node_modules"
        ]
    }

     

  2. 相關文件夾新建:先新建src/index.ts這點很重要,防止無法找到主目錄)再新建src/controller(用於文件調用)
  3. 打開終端:分界面:1界面輸入:tsc -w ;1界面輸入:yarn 或者 yarn init -y 用於初始化;初始化完成後,輸入:
    yarn add @ctsy/server @ctsy/controller @ctsy/model @ctsy/relation @ctsy/config @ctsy/router @types/node 
     用於依賴包的安裝。安裝完成後,可以在 node_modules 文件夾中找到這些依賴包
  4. 打開index.ts文件,輸入: 用於配置後臺服務
    import server from '@ctsy/server'
    import {install as RouterInstall} from '@ctsy/router'
    server.install({install : RouterInstall})
    server.start(9600);//設置端口

     

  5. src/controller文件夾新建文件 A.ts 並寫入相關函數: 用於確定交互成功
    export default class A{
        a(){
            return 1;
        }
    
        b(){
            return 2;
        }
    }

     

  6. 開始配置調試文件:打開 .vscode/launch.json 文件,輸入相關,再在調試處點擊 server-9600 開始運行
    {
                "type": "node",
                "request": "launch",
                "name": "server-9600",
                "cwd": "${workspaceFolder}",
                "program": "${workspaceFolder}/dist/index.js"
            },

     

  7. 瀏覽器中輸入 http://localhost:9600/A/a 和  http://localhost:9600/A/b 根據對應結果確定是否完成交互,返回:                  a:{"d":1,"c":200,"i":"","e":""}        b:{"d":2,"c":200,"i":"","e":""}     即表明交互成功
  8. 升級:調用本地文件並顯示: 新建文件夾data ,添加文件 test.txt ;將 A.ts 文件修改爲:
    import { readFile } from "fs";
    export default class A{
        a(){
            return 1;
        }
    
        b(){
            return 2;
        }
        fun(){
            return new Promise((s)=>{
            //調用文件:test.txt
                readFile('data/test.txt',(e,d)=>{
                    s(d.toString())
                })
            })
        }
    }

    打開文件 test.txt(文本),添加任意內容,保存後運行,瀏覽器輸入:http://localhost:9600/A/fun,於 “d”:中顯示相關內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章