【发布时间】: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);
这是我得到的一个错误:
如果我从 Angular 为我的“发布方法”添加额外选项并编写如下内容:
this.http.post('/api/upload', body, {responseType: 'text'})
.subscribe();
加上responseType: 'text'这个错误已经不存在了,但是当涉及到console.log的所有数据,我贴出来的表达,undefined:
我做错了什么?
【问题讨论】:
-
另外,您的 req.body 似乎不包含任何“任务”、“类型”或“主题”。您可以通过 console.log JSON.stringify(req.body) 查看实际对象内部的内容(而不是获取“[object Object]”
-
显示body包含:{}
-
我最初的直觉猜测是您不能将数组作为发布请求的顶级“容器”发送。尝试只发送一个对象,看看会发生什么。
-
Cody,我刚刚尝试过,但在 Express 的 post 请求中仍未定义。
标签: javascript node.js angular express