【问题标题】:Problem with sending data from Angular to Express将数据从 Angular 发送到 Express 的问题
【发布时间】:2021-03-31 07:19:30
【问题描述】:

我正在尝试将数据从 Angular 发布到 Express.js

这是我连接到按钮的函数(TypeScript):

  upload(): void {
    const nameFromId = document.getElementById('taskName') as HTMLInputElement;
    this.taskName = nameFromId.value;

    const testData = [
      {
        task: this.taskName,
        selectedType: this.selectedType,
        selectedSubject: this.selectedSubject
      }
    ];
    const body = JSON.stringify(testData);
    this.http.post('/api/upload', body)
      .subscribe();

“body”不为空

这是快递:

const express = require('express');
const path = require('path');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');


app.use(bodyParser.urlencoded({
  extended: true
}));


app.post('/api/upload', (req, res) => {
  let task = req.body.task;
  let selectedType = req.body.selectedType;
  let selectedSubject = req.body.selectedSubject;

  console.log("task: " + task);
  console.log("type: " + selectedType);
  console.log("subject: " + selectedSubject);
  console.log("server: " + req.body);
  res.end("yes");
})

app.use(express.static(__dirname + '/dist/al'));

app.get('/*', function (req, res) {

  res.sendFile(path.join(__dirname + '/dist/al/index.html'));
});

app.listen(process.env.PORT || port);

这是我得到的一个错误:

mistake from console

如果我从 Angular 为我的“发布方法”添加额外选项并编写如下内容:

this.http.post('/api/upload', body, {responseType: 'text'})
      .subscribe();

加上responseType: 'text'这个错误已经不存在了,但是当涉及到console.log的所有数据,我贴出来的表达,undefined:

Express console.log

我做错了什么?

【问题讨论】:

  • 另外,您的 req.body 似乎不包含任何“任务”、“类型”或“主题”。您可以通过 console.log JSON.stringify(req.body) 查看实际对象内部的内容(而不是获取“[object Object]”
  • 显示body包含:{}
  • 我最初的直觉猜测是您不能将数组作为发布请求的顶级“容器”发送。尝试只发送一个对象,看看会发生什么。
  • Cody,我刚刚尝试过,但在 Express 的 post 请求中仍未定义。

标签: javascript node.js angular express


【解决方案1】:

您正在发送一个字符串作为 http 请求正文。 不要使用 JSON.stringify,尝试按原样发​​送对象。

const testData = [
      {
        task: this.taskName,
        selectedType: this.selectedType,
        selectedSubject: this.selectedSubject
      }
    ];

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
    })
}

this.http.post('/api/upload', testData, httpOptions)
  .subscribe();

将此行添加到服务器:

app.use(bodyParser.json());

最后:

const bodyParser = require('body-parser');    
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

【讨论】:

  • 我刚试过,还是不行
  • 你在发布中间件之前使用了body-parser模块吗? const bodyParser = require('body-parser');常量应用程序 = 快递(); app.use(bodyParser.urlencoded({extended: true }));
  • andellapie,不,我不是。但是我刚刚尝试使用它仍然无法正常工作
  • 我已经用 httpOptions 更新了我的答案。试一试
  • andellapie,我刚刚更新了我的程序和上面的帖子,但仍然无法定义。我认为我的前端发布请求有问题。因为即使在我使用 JSON.parse(req.body) 时,它也显示为“{}”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多