【问题标题】:How to call node.js (or express) functions from Type Script如何从 Type Script 调用 node.js(或 express)函数
【发布时间】:2021-07-03 16:52:22
【问题描述】:

我在 Node.js 中创建了一个名为GetFileNames() 的函数,该函数返回一个字符串数组。

现在我想在我的 TS 脚本中调用它并用它来填充本地数组。

问题是我不知道如何调用这个函数。有人可以帮帮我吗?

【问题讨论】:

    标签: node.js angular typescript


    【解决方案1】:

    您需要一个中间件,例如 express 并从您的 .ts 文件调用服务(通过 ng generate service someservice 生成),然后向您的节点路由发出请求,这里有一个小例子来说明我的意思:

    somecomponent.ts:

    import { someService } from 'src/app/services/someservice.service';
    ...
    ..
    files = []
    
      /* INFO: Function for getting all files */
      getAllFiles() {
        this.someservice.getAllFiles().subscribe((res) => {
          if (!res.success) {
            this.files = [];
          } 
          else {
            this.files = res.data;
          }
        });
      }
    

    someservice.service.ts:

    import { Injectable } from '@angular/core';
    import { environment } from '../../environments/environment';
    import * as rxjs from 'rxjs';
    import { HttpHeaders, HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class someService {
    ....
    ...
    ..
    
      // INFO: Function to create headers, add token, to be used in HTTP requests
      createAuthenticationHeaders() {
        this.loadToken(); // INFO: Get token so it can be attached to headers
        // INFO: Headers configuration options
        this.options = new HttpHeaders({
          'Content-Type': 'application/json',
          'authorization': this.authToken
        });
      }
    
      /*  INFO: service for getting files from filesystem */
      getAllFiles() {
        this.createAuthenticationHeaders();
        if (environment.production == true || environment.marker == true) {
          let apiURL = '/someroute/getAllFiles';
          return this.httpClient.get<any>(apiURL, { headers: this.options });
        }
        else {
          let apiURL = `http://localhost:${environment.port}/someroute/getAllFiles`;
          return this.httpClient.get<any>(apiURL, { headers: this.options });
        }
      }
    
    
    }
    

    someroute.js:

    module.exports = (router) => { 
    
       router.get('/getAllFiles', (req, res) => {
          filenames = fs.readdirSync(`some/path/to/files`);
          res.json({ success: true, data: filenames });
        });
    
       return router;
    }
    

    显然这只是一个最小的示例,您需要自己处理错误处理等(例如,以防目录不存在)。前端和后端之间的身份验证相同。在您的 app.js 中,您需要 require 路由并通过 app.use('/someroute', someRoute);“使用”它

    澄清来自 cmets 的问题的附件:

    这是一个非常常见的技术栈(这里有一个额外的数据库):

    这是一个常见项目架构的示例:

    --projectroot
        |___ app.js
        |
        |___ /client   // your frontend app (i.E. Angular, React etc..)
        |      |
        |      |___ /node-modules  // node-modules for frontend defined in package.json
        |      |___ /src
        |             |
        |             |___ /app  // web-app with components, serives, assets etc
        |                     |___/components
        |                     |___/services
        |                     |___/assets
        |
        |___ /node-modules  // node-modules for backend defined in package.json
        |
        |___ /routes   // route-files 
    

    【讨论】:

    • 非常感谢您的回答,非常感谢!几个问题,我对WebDev完全陌生,如果我的JS脚本在myservice-serivice/public/javascripts/myScript.js里面可以吗?在这种情况下,假设函数所在的脚本名称为 myScript.js。
    • @AlessandroCinque 如果您正在后端/服务器中执行操作,例如文件系统上的操作,并且希望将结果传递给前端(例如 Web 应用程序),那么进行这些操作是有意义的在 projectroot/routes 的某个地方.. - 我将在我的答案中添加一些架构信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2019-03-20
    • 2015-11-12
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多