首页 文章

无法在Ionic 3 / Angular 5中发送HTTP POST请求

提问于
浏览
0

我正在尝试从我的 Ionic 3 (Angular 5) 应用程序向我的REST api发送一个帖子请求,但我得到 HTTP 404 (Not found)HTTP 400 (Bad request) .

当我使用Postman发送帖子请求时,它是成功的 . 此外,我在Ionic 3应用程序中的GET请求也能成功运行 . 您可以在下面看到成功请求,它没有授权:

这是我的请求方法:

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));
    })
  }

使用标头我得到HTTP 404(未找到)但没有HTTP 400(错误请求) . 所以,我尝试使用和不使用 Headers 的不同身体对象 . 这是我的用法而不是 FormData body对象:

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" });

并尝试这些情况发送头而不是上面的 Headers :

let Options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};
-----
let headers = { 'Content-Type': 'application/json' }

它们都没有成功 . 你能说出正确的方法吗?

1 回答

  • 0

    我找到了解决方案 . 问题是我的RESTful api阻止了ajax发布请求 . 这是Asp.Net WebApi 2中与Cors相关的解决方案:

    Startup.csStartup 类中添加一个常量:

    private const string DefaultCorsPolicyName = "localhost";
    

    将Cors添加到 Startup 类的 ConfigureServices 方法中:

    services.AddCors(options =>
        {
            options.AddPolicy(DefaultCorsPolicyName, builder =>
            {        
                  builder
                  .AllowAnyOrigin() 
                  .AllowAnyHeader()
                  .AllowAnyMethod();
            });
        });
    

    Startup 类的 Configure 方法中启用Cors:

    app.UseCors(DefaultCorsPolicyName); //Enable CORS!
    

    在web.config中删除 first 自定义标头:

    <add name="Access-Control-Allow-Origin" value="*"/>
    

相关问题