[英]Can't send an HTTP POST request in Ionic 3 / Angular 5
I'm trying to send a post request from my Ionic 3 (Angular 5) app to my REST api, but I'm getting HTTP 404 (Not found) or HTTP 400 (Bad request) . 我正在尝试将Ionic 3(Angular 5)应用中的发布请求发送到我的REST api,但是我正在获取HTTP 404(未找到)或HTTP 400(错误请求) 。
When I send the post request using Postman it is successful. 当我使用Postman发送发帖请求时,它是成功的。 And also, my GET request in Ionic 3 app works successfully.
而且,我在Ionic 3应用程序中的GET请求成功运行。 You can see success request below, it hasn't an Authorization :
您可以在下面看到成功请求,它没有授权 :
Here is my request method: 这是我的请求方法:
sendConfirmationCode() {
let mybody = new FormData();
mybody.append('msisdn', '1234567');
let myheaders = new HttpHeaders({
'Content-Type': 'application/json'
});
this.http.post('http://mydomain/methodname', mybody, {headers: myheaders})
.subscribe(data => {
console.log(JSON.stringify(data));
}, error => {
console.log(JSON.stringify(error));
})
}
With headers I get HTTP 404 (Not found) but without HTTP 400 (Bad request). 使用标头,我得到HTTP 404(未找到),但是没有 HTTP 400(错误请求)。 So, I tried different body objects with and without using headers.
因此,我尝试使用和不使用标头的不同主体对象。 Here is my usings instead of
FormData
body object: 这是我的用法,而不是
FormData
主体对象:
let mybody= new HttpParams();
mybody.append('msisdn', '1234567');
-----
let mybody= new URLSearchParams()
mybody.append('msisdn', '1234567');
-----
//SubscriberDataInput is my class for to use as input body model of api's method
let mybody = new SubscriberDataInput();
mybody.msisdn = '1234567';
-----
let mybody = JSON.stringify({ "msisdn": "1234567" });
And tried these cases for sending header instead of above header: 并尝试了以下情况以发送标头而不是上面的标头:
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
-----
let headers = { 'Content-Type': 'application/json' }
None of them works successfully. 他们都不成功。 Can you please tell the right way?
你能告诉正确的方法吗?
I found the solution. 我找到了解决方案。 The problem was my RESTful api prevents ajax post requests.
问题是我的RESTful API阻止了ajax发布请求。 This is a solution in Asp.Net WebApi 2 which related Cors:
这是Asp.Net WebApi 2中与Cors相关的解决方案:
Add a constant into Startup
class of Startup.cs : 将常量添加到Startup.cs的
Startup
类中:
private const string DefaultCorsPolicyName = "localhost";
Add Cors into ConfigureServices
method of Startup
class: 将Cors添加到
Startup
类的ConfigureServices
方法中:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Enable Cors in Configure
method of Startup
class: 在
Startup
类的Configure
方法中启用Cors:
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
Delete first custom header in web.config: 删除web.config中的第一个自定义标头:
<add name="Access-Control-Allow-Origin" value="*"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.