如果您可以发布 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 应用程序提供了一个良好的开端。