最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

创建一个宁静的api端点,以便可以将我的angular 8应用程序连接到它

运维笔记admin5浏览0评论

创建一个宁静的api端点,以便可以将我的angular 8应用程序连接到它

创建一个宁静的api端点,以便可以将我的angular 8应用程序连接到它

我是angular和node.js的新手,想知道如何解决以下问题。因此,我在前端使用了angular 8应用程序,并尝试将其连接到后端的node.js应用程序。可以在此处()找到该节点应用程序的github。节点应用程序具有用于路由的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文件,一旦我进入节点应用程序的域,就可以在我的角度应用程序中使用该文件来构建我的UI。我知道大多数逻辑都在app.js文件中,但不是json格式。我不知道如何编辑app.js文件以使其为json并最终将其连接到index.js文件,以便能够通过角度应用程序访问它。

谢谢您的帮助。

回答如下:

如果您可以发布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 Side:]

在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应用程序的良好开端。

发布评论

评论列表(0)

  1. 暂无评论