简体   繁体   中英

Post request doesn't reach Node from Angular

I'm triggering this function called upload() by clicking on submit button on the frontend.

in my app.html:

<div class="row" style="padding:10px;">
        <button type="submit" class="btn btn-primary" style="margin-left:10px;" (click)="upload()">Submit</button>
    </div>

in my app.ts:

upload() {

    this.files = {
      pdf_one: './server/test-pdfs/pdf-sample.pdf',
      pdf_two:  './server/test-pdfs/pdf-sample.pdf',
    };

    this.filesToUpload = [];

    this.filesToUpload.push(this.files.pdf_one);
    this.filesToUpload.push(this.files.pdf_two);

    this.getMergedPDF(this.filesToUpload);
}

getMergedPDF(filesToUpload): Observable<string> {
        return this.http.post<string>('http://localhost:8081/merge-pdf', JSON.stringify(filesToUpload));
 }

I've set breakpoints and the function above is being called just fine. It's just when it gets to the node.js side, nothing is triggered.

Here's how I set the api endpoint on nodejs side: server.js

app.post('/merge-pdf', (req, res) => {
    this.fileList  = req;

    PDFMerge(this.fileList, {output: `${__dirname}/test-pdfs/merged-pdf.pdf`});
    res.send(200);
});

const server = app.listen(8081, () => {
    console.log('Listening on port %s...', server.address().port);
});

I was wondering what I could be doing wrong above that the api endpoint is not triggered?

EDIT:

I've tried this:

getMergedPDF(filesToUpload): Observable<string> {
    return this.http.post<string>('http://localhost:8081/merge-pdf', JSON.stringify(filesToUpload))
    .subscribe(data  => this.mergedUrl = data);
  }

But this error happens:

Type 'Subscription' is not assignable to type 'Observable<string>'.
  Property '_isScalar' is missing in type 'Subscription'.'

You need to subscribe to it. Observables are lazy, and won't actually perform the POST call unless you subscribe to it.

this.http.post(...).subscribe(...)

You can make sure Node is not in fault by checking your browser's Network tab and see that no HTTP call is made in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM