我有一个nodejs作为后端服务,而Angular 5作为前端,我想对NodeJS Server调用POST方法,将一个Blob文件发送到服务器。
但是该post方法已执行,后端控制台日志中未显示任何内容。
以下是一些代码段:
server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(cors());
//create a cors middleware
app.use(function (req, res, next) {
//set headers to allow cross origin request.
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/decrypt', function (req, res) {
console.log("decrypt called");
return 'data back';
})
在AngularJS中: database.services.ts:
import { Injectable, Input } from '@angular/core';
import { Http, Response, ResponseContentType } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Observable';
import { saveAs, FileSaver } from 'file-saver/FileSaver';
import { HttpClientModule, HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
@Injectable()
export class DatabaseService {
private API_GET_LIST_FILES = 'http://localhost:3000/files';
private BASE_URL = 'http://localhost:3000/';
private API_GET_FILE = 'http://localhost:3000/download?name=';
constructor(private http: Http) { }
getFile(key: string) {
return this.http.get(this.API_GET_FILE + key, {
responseType: ResponseContentType.Blob
})
.map(res => {
return {
filename: key.split('/').pop(),
data: res.blob()
};
})
.subscribe(res => {
this.decryptFile(res.data);
saveAs(res.data, res.filename);
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.');
})
}
decryptFile(data: any): Observable<any> {
const httpOptions = {
Headers: new HttpHeaders({
'Content-Type': 'application/octet-stream',
'data': data
})
};
console.log(data, typeof data, this.BASE_URL + `decrypt`);
return this.http.post(`http://localhost:3000/decrypt`, httpOptions);
}
}
当我单击页面上的文件下载按钮时,将调用此getFile函数,因为在浏览器控制台中,它将打印出Blob(564534) {size: 564534, type: "application/octet-stream"} "object" "http://localhost:3000/decrypt"
我希望nodejs服务器采用此post方法和Blob(GPG文件)对象作为参数,并执行某些操作。
但是看起来后端服务器没有打印出任何东西。
请告知如何修改此代码,我应该使用POST还是PUT?我想将GPG文件传递到nodeJS服务器并对其解密。
谢谢
答案 0 :(得分:1)
decryptFile
返回Observable
,您必须订阅它才能执行http调用:
this.decryptFile(res.data).subscribe(decrypted => {???});
编辑:不能抗拒,一些观察,随便忽略:
HttpClient
开始使用@angular/common/http
,而不是Http
。好消息是您已经进口了。