Angular 7 不发送 HTTP Post 请求数据 [英] Angular 7 not sending HTTP Post request data
问题描述
我正在尝试向我使用 ExpressJS 开发的 REST API 发送 HTTP Post 请求.我正在使用 Angular 的 HttpClient 使用以下服务文件发送请求:
I'm trying to send an HTTP Post request to a REST API I developed using ExpressJS. I'm using Angular's HttpClient using the following service file to send requests:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJ0ZXN0MiIsImxldmVsIjoxLCJpYXQiOjE1NTYyMDU0OTMsImV4cCI6MTU1NjI5MTg5M30.luqbDb-sSLxsX0LKFTaF6NTYDO4tS6kCI8V_d9pizmA'
})
};
@Injectable({
providedIn: 'root'
})
export class ApiserviceService {
constructor(private http: HttpClient) { }
getData(url: string) {
return this.http.get(url)
}
postData(url: string, data: Object) {
console.log(data);
return this.http.post(url, data, httpOptions)
}
}
使用以下代码调用服务:
Calling the service using the following code:
/* other Component class code */
constructor(private data: ApiserviceService) {}
submit()
{
let url: string =
"http://xxx.xxx/api/hotels/"
+ this.route.snapshot.params.hotelId
+ "/reviews";
this.data.postData(url, this.revForm.value).subscribe(data => {
console.log(data);
this.router.navigate(['/']);
});
}
我不得不添加授权标头,因为 API 将拒绝所有不携带令牌的请求.
I had to add an authorization header since the API will reject all requests which do not carry a token.
在服务文件中 http.post 语句正上方的控制台日志中,我完全按照需要获取数据,一个带有所有必需参数的 JSON 对象打印在 Google Chrome 的控制台上.但是,出于某种原因,angular 应用发送了一个空请求.
In the console log just above the http.post statement in the service file, I'm getting the data exactly as desired, a JSON object with all the required parameters being printed on Google Chrome's console. However, for some reason the angular app is sending an empty request.
我在响应中收到一个缺失值错误,因此为了找出原因,我在 API 控制器中添加了以下行来处理错误:
I was getting a missing values error in the response, so in order to figure out the reason, I added the following line in the API controller along the error handling:
console.log(req.body);
console.log(req.body);
这是来自 API 的函数:
Here's the function from the API:
var _addReview = function(req, res, data) {
data.reviews.push({
name : req.body.name,
rating : parseInt(req.body.rating, 10),
review : req.body.review,
id : req.userid
});
data.save(function(err, hotelUpdated){
if(err) {
console.log(req.body);
res.status(500).json(err);
}
else {
res.status(201).json(hotelUpdated.reviews[hotelUpdated.reviews.length - 1]);
}
});
};
NodeJS 的控制台打印了一个空对象 {}.我尝试将 Content-Type 更改为 application/json 但仍然没有运气.
NodeJS's console printed an empty object {}. I tried changing the Content-Type to application/json but still no luck.
我还在 NodeJS 控制台中注意到我的 Angular 应用程序在 POST 请求之前发送了一个 OPTIONS 请求.我上网查了一下,发现只有在OPTIONS请求返回200码后才会发送POST请求.但是我的 POST 请求正在发送,因为我收到了响应.所以我相信 OPTIONS 请求正在成功.
I also noticed in the NodeJS console that my Angular app is sending an OPTIONS request before the POST request. I checked online and found that the POST request will only be sent once the OPTIONS request returns a 200 code. However my POST request is being sent, since I am receiving a response. So I believe that the OPTIONS request is getting successful.
我的 API 在 Postman 中运行良好,即使我发送的标头与在 Angular 应用中的标头完全相同.
My API works perfectly in Postman, even when I send the exact same headers as I am in the Angular app.
推荐答案
通过使用 Content-Type: application/json 而不是 application/x-www-form-urlencoded 发送请求解决了问题.显然,Angular 并没有像 Postman 那样将 application/x-www-form-urlencoded 转换为 json-parseable 数据.
Solved the problem by sending the request with Content-Type: application/json instead of application/x-www-form-urlencoded. Apparently Angular was not converting application/x-www-form-urlencoded to json-parseable data like Postman was.
这篇关于Angular 7 不发送 HTTP Post 请求数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!