我正在尝试从客户端(在 Angular 中)获取数据到 Nodejs 服务器。
在 Angular 中,我声明了一项服务。
export class AddTaskService {
constructor(private http: HttpClient) { }
url = 'http://localhost:3000/tasks';
posttasks(task) {
return this.http.post<string>(this.url, JSON.stringify({ task: task }));
}
}
在服务器中我添加了 bodyparser 并配置了它
index.js
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
路由器.js
router
.route("/tasks")
.post(function (req, res) {
var taskModel = new taskSchema();
taskModel.task = req.body.task;
console.log(req.body);
taskModel.save(function (err) {
if (err) {
res.send(err);
}
res.json({
message: "nouvProj created!"
});
});
});
使用带有x-www-form-urlencoded
的 postman 可以工作,但是在Angular中,当我发送数据时req.body
为空
编辑: 这是 url 网络详细信息: 一般
Request URL: http://localhost:3000/tasks
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
响应 header
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: GET, POST, PUT ,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Sun, 27 May 2018 19:24:57 GMT
ETag: W/"1f-NlZ/5EsK7Z/S3Ze5LQN4AonQQ90"
X-Powered-By: Express
请求 header
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,ar-TN;q=0.8,ar;q=0.7,en-US;q=0.6,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 14
Content-Type: text/plain
DNT: 1
Host: localhost:3000
Origin: http://localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
请求负载
{task: "klj"}
task
:
"klj"
最佳答案
您可以将 HTTP header 作为选项传递:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
})
}
return this.http.post<string>(this.url, task, httpOptions);
关于node.js - 从 Angular 向服务器发送数据时请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555535/