【问题标题】:NodeJS server can't retrive post data from AngularNode JS 服务器无法从 Angular 检索发布数据
【发布时间】: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}作为正文传递

标签: node.js angular express


【解决方案1】:

按照 Anand 的建议,将标头设置为 application/json(或完全跳过 httpOptions,因为这是默认设置)并发送 {name: res}。那么请求正文应该就是这样。

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

Express 方法回调签名是(req, res, next) 而不是(res, req),阅读您的代码时会感到困惑:(

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

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 2017-06-15
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多