【问题标题】:Create a restful api endpoint so that I can connect my angular 8 app to it创建一个宁静的 api 端点,以便我可以将我的 angular 8 应用程序连接到它
【发布时间】:2020-01-22 17:18:42
【问题描述】:

我是 angular 和 node.js 的新手,想知道如何解决以下问题。因此,我在前端使用 angular 8 应用程序,并尝试将其连接到作为后端的 node.js 应用程序。可以在此处找到节点应用程序的 github (https://github.com/pepzwee/node-csgo-web-tradebot)。节点应用程序有一个用于路由的 index.js 文件、一个用于显示内容的 index.html 文件和一个用于逻辑的 app.js 文件(位于:static/js/app.js)。现在,我希望能够摆脱 index.html 以便我可以使用我的 Angular 应用程序并使用 ff 连接端点:

app.get('/', (req, res) => {
    //give access endpoint to angular app by accessing json format
})

这样我就可以获得一个包含可用方法和变量的 json 文件,一旦我进入节点应用程序的域,我就可以在我的 Angular 应用程序中使用这些文件来构建我的 UI。我知道大部分逻辑都在 app.js 文件中,但不是 json 格式。我不知道如何编辑 app.js 文件以使其成为 json 并最终将其连接到 index.js 文件,以便能够通过 Angular 应用程序访问它。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript node.js angular api express


    【解决方案1】:

    如果您可以发布 app.js,这将有助于准确了解您的应用是如何设置的。我不完全确定您将 app.js 设为 JSON 是什么意思?但这里有一个将两者联系起来的粗略想法。

    节点端 app.js:

    要将 index.js 链接到您的应用,您可以在 app.js 中执行以下操作:

    const express = require('express');
    const router = express.Router();
    
    const indexFile = require('<relative-path-to-index-file>');
    
    router.use('/indexFile', indexFile); // this would give you the endpoint localhost:3000/indexFile
    

    然后在 index.js 中如下:

    const express = require('express');
    const router = express.Router();
    
    router.get('/get', (req, res) => {
    
    })
    
    router.post('/post', (req, res) => {
        // to access body from angular use req.body
        // to send data back use req.send() or req.json() for JSON object
    })
    
    module.exports = router;
    

    这将允许您拥有一个单独的文件,其中包含您的端点。

    角边:

    在 Angular 上,我会创建一个服务。您可以创建一个文件name.service.ts 并使用以下通用代码。

    import {Injectable} from '@angular/core';
    import {HttpClient} from '@angular/common/http';
    
    @Injectable()
    export class NameService {
    
      constructor(private http: HttpClient) {
      }
    
      serviceMethodPost(body) {
        return this.http.post('localhost:3000/indexFile/post', body);
      }
    
      serviceMethodGet() {
        return this.http.get('localhost:3000/indexFile/get');
      }
    }
    

    然后在您希望使用的任何控制器中发出请求:

    constructor(private nameService: NameService) { } // make sure to import at the top
    
    ...
    
    this.nameService.serviceMethodPost(body).subscribe(returnedValue => {
        // do any logic you would like with the returned value or when request complete          
    });
    
    this.nameService.serviceMethodGet().subscribe(returnedValue => {
        // do any logic you would like with the returned value or when request complete          
    });
    

    希望这为您连接 Node 和 Angular 应用程序提供了一个良好的开端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 2017-10-31
      • 2017-11-02
      • 1970-01-01
      • 2022-06-30
      • 2021-11-27
      • 2015-09-04
      • 2020-05-31
      相关资源
      最近更新 更多