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) .
When I send the post request using Postman it is successful. And also, my GET request in Ionic 3 app works successfully. 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). So, I tried different body objects with and without using headers. Here is my usings instead of FormData
body object:
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. This is a solution in Asp.Net WebApi 2 which related Cors:
Add a constant into Startup
class of Startup.cs :
private const string DefaultCorsPolicyName = "localhost";
Add Cors into ConfigureServices
method of Startup
class:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Enable Cors in Configure
method of Startup
class:
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
Delete first custom header in web.config:
<add name="Access-Control-Allow-Origin" value="*"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.