【发布时间】:2018-07-31 19:36:45
【问题描述】:
我有一个用 NodeJS 编写的后端服务器,它使用 express。
我有最新的 Angular 作为前端,我将数据(GPG 文件)发布到 nodeJS 服务器,我尝试在 NodeJS 代码中获取该数据,并在服务器控制台中打印出来,但我得到的只是一个空对象。
我要做的就是将 Blob 数据传递给节点服务器,或者将纯文本传递给节点服务器,然后从节点代码中读取它。
const express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
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();
});
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/decrypt', (res, req) => {
// Here I try to access the data that I passed by POST method
console.log(res.body);
return 'data back';
})
这是我的 Angular 代码:
import { Injectable, Input } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Observable';
import { saveAs } from 'file-saver/FileSaver';
@Injectable()
export class DatabaseService {
private API_GET_LIST_FILES = 'http://localhost:3000/files';
private API_GET_FILE = 'http://localhost:3000/download?name=';
private BASE_URL = 'http://localhost:3000/';
constructor(private http: HttpClient) { }
getFile(key: string) {
return this.http.get(this.API_GET_FILE + key, {
responseType: 'blob'
})
.map(res => {
return {
filename: key.split('/').pop(),
data: res
};
})
.subscribe(res => {
console.log('start download:', res);
// no matter what I pass here to the decrypt function, I can't get it in nodeJS server
this.decrypt(res.filename)
.subscribe(
next => console.log(next)
);
saveAs(res.data, res.filename);
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.');
});
}
decrypt(res): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/octet-stream'
})
};
return this.http.post(this.BASE_URL + 'decrypt', res, httpOptions);
}
}
如果我将***res*** 传递给解密函数,我会得到很多信息,但对我来说看起来很奇怪。
【问题讨论】:
-
你为什么只在前端的
decrypt方法中传递res.filename?在向后端发出请求时,您将标头设置为application/octet-stream但您只是将字符串作为正文传递:/ -
@AnandUndavia ,代码上方有一条注释说“//无论我在这里传递什么给解密函数,我都无法在 nodeJS 服务器中获取它”
-
@AnandUndavia 好问题,但即使我通过 res 本身,我也无法在节点服务器控制台中的任何位置归档文件名
-
@ramasCoder 同意,但问题在于标题。因为在后端,express 只知道如何解析
application/json,以及bodyParser.urlencoded()支持的其他表单头。前端说我会发送application/octet-stream,但会发送一个字符串。而后端甚至不知道如何解析application/octet-stream -
@XinruiMa,试试这个:将标题设置为
application/json,并将{name: res}作为正文传递