http发布请求在ionic应用程序中不起作用,但相同的发布请求在postman中有效

时间:2019-05-04 05:23:15

标签: angular typescript http ionic3 apache-cordova

我试图在Visual Studio的ionic v3中制作一个应用程序(适用于Apache Cordova的工具)。在应用程序屏幕之一中,我从用户那里获取信息并将其发送到api。问题是我发出的http发布请求无法正常工作。如果我从邮递员发出相同的请求,则它会起作用,而不是在我的应用程序页面中起作用

我尝试了所有答案,但找不到任何帮助。我尝试添加我随请求传递的更改标头(传递“用户代理”)

 let header = new Headers({
   'Content-Type': 'application/json; charset=utf-8',
   'Authorization': 'console',
   'MacAddress': localStorage.getItem('macAddress'),
   'Key': localStorage.getItem('key'),
   'access-control-allow-origin': '*',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
 });
 let data = JSON.stringify({
   FirstName: this.FirstName,
   LastName: this.LastName,
   MI: this.u_mname,
   Address: this.Address,
   City: this.City,
   State: this.State,
   ZipCode: this.ZipCode,
   HomePhone: this.HomePhone,
   OfficePhone: this.OfficePhone,
   OfficePhoneExt: this.OfficePhoneExt,
   CellPhone: this.CellPhone,
   Fax: this.Fax,
   Email1: this.Email1,
   Email2: this.Email2,
   ContactTypeId: this.ContactTypeId,
   dob: this.dob,
   ApplicationId: this.ApplicationId
 });

 this.http.post(localStorage.getItem('base_url') + '/services/odata/tblContacts?Mother=0&Father=0&Guardian=0&groupIdList=0', data, { headers: header})
   .map(res => console.log(res))
   .subscribe(
      data => {
       alert(data)
     }, err => {
       alert(err)
     })

我希望响应应该是“ http状态代码201”,但是我却收到状态代码200和消息“内部服务器错误”。请查看服务器日志的详细信息。'

1 个答案:

答案 0 :(得分:0)

您可以尝试这些。

public httpOptions;

this.httpOptions = {
      headers: new HttpHeaders({ 
   'Content-Type': 'application/json; charset=utf-8',
   'Authorization': 'console',
   'MacAddress': localStorage.getItem('macAddress'),
   'Key': localStorage.getItem('key'),
   'access-control-allow-origin': '*',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
   })
    };

 let data = JSON.stringify({
   FirstName: this.FirstName,
   LastName: this.LastName,
   MI: this.u_mname,
   Address: this.Address,
   City: this.City,
   State: this.State,
   ZipCode: this.ZipCode,
   HomePhone: this.HomePhone,
   OfficePhone: this.OfficePhone,
   OfficePhoneExt: this.OfficePhoneExt,
   CellPhone: this.CellPhone,
   Fax: this.Fax,
   Email1: this.Email1,
   Email2: this.Email2,
   ContactTypeId: this.ContactTypeId,
   dob: this.dob,
   ApplicationId: this.ApplicationId
 });

 this.http.post(
  localStorage.getItem('base_url') + '/services/odata/tblContacts?Mother=0&Father=0&Guardian=0&groupIdList=0', 
data,
httpOptions
}).map(res => console.log(res))
  .subscribe(
     data => {
       alert(data)
     }, err => {
       alert(err)
     })