NodeJS服务器无法从Angular检索发布数据

时间:2018-07-31 19:36:46

标签: node.js angular express

我有一个用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';
})

enter image description here

这是我的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***传递给解密函数,我会得到很多信息,但对我来说却很奇怪。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

执行Anand的建议,将标头设置为application/json(或者完全跳过httpOptions,因为这是默认设置),然后发送{name: res}。然后请求正文应该就是那个。

对于文件上传,您应该使用Express中间件,例如MulterMultiparty。例如在ng2-file-upload的角度上。

Express方法的回调签名是(req, res, next)而不是(res, req),在读取代码时会造成混淆:(

如果您只是从回调中return,它将挂起直到http请求超时(我认为)。您应该进行res.status(200).end()res.json({done: true})或类似的操作。