用按钮下载文档的角度:为什么http POST方法无法正常工作

时间:2019-06-16 11:57:51

标签: node.js angular express http

我试图使用前端中的Angular和后端中的Express / Node.js单击按钮来实现文档下载功能。
enter image description here
这是宏伟的按钮:
enter image description here

这是前端代码:

  

app.component.ts

import { Component } from '@angular/core';
import {GenerateReportService} from './services/generate-report.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private generateReportService:GenerateReportService) { }
  generateReport() {
   this.generateReportService.generateReport();
  }
}
  

app.component.html

<button  color="primary" (click)="generateReport()">Generate report</button>
<router-outlet></router-outlet>
  

generate-report.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class GenerateReportService {
  uri = 'http://localhost:5353';
  constructor(private http: HttpClient) {}
  generateReport() {
    // docInfo will be edited after I manage to download a document with a click of a button --'
    const docInfo = {};
    return this.http.post(`${this.uri}/generateReport`, docInfo);
  }
}

这是后端代码:

  

server.js

const bodyParser = require('body-parser');
const cors = require('cors')
const express = require('express');
const app = express();
const router = express.Router();
const path = require('path');


app.use(cors());
app.use(bodyParser.json());

router.route('/generateReport').post((req, res) => {
    setTimeout(() => {
        res.download(path.join(__dirname, 'docs/doc1.txt'), function (err) {
            console.log(err);
        });
    }, 500)

});


app.use('/', router);

app.listen(5353, () => console.log('Express server running on port 5353'));

最后,这是docs文件夹,其中包含要下载的文档:
enter image description here

从那时起,我在没有Angular的另一个项目中测试了后端代码,并且该代码可以正常工作。我相信问题在于前端代码,尤其是

中的此方法
  

generate-report.service.ts

  generateReport() {
    // docInfo will be edited after I manage to download a document with a click of a button --'
    const docInfo = {};
    return this.http.post(`${this.uri}/generateReport`, docInfo);
  }

当我单击按钮时,没有任何错误。但是,该文档未下载。
谁能告诉我我做错了什么以及如何解决?
谢谢!

0 个答案:

没有答案