使用Angular发布方法时,从API接收到的响应数据为空,但状态为200

时间:2019-09-08 11:48:07

标签: angular cors

我想使用Angular的post方法,从第三个API接收响应数据(JSON)。当使用Angular将请求发送到API时,控制台中的响应状态为200。但是,我没有收到任何数据作为响应,即

Response {_body: "", status: 200, ok: true, statusText: "OK"}    

,然后是

跨源读取阻止(CORB)阻止了跨源响应

https://theLink/ThatI/wantToUse/customer/complaintlist with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. 

我已经联系了API开发人员,他已经在他的API中更新了CORS配置。因此,我不知道为什么我没有收到响应数据。

这是server.service.ts代码:

import { Injectable } from "@angular/core";
import { Headers,Http} from "@angular/http";
@Injectable()
export class ServerService {
   constructor (private http: Http) {}
  storeServer(servers:any[]){
      const headers=new Headers({'Content-Type': 'application/json'});
  return this.http.post('https://theLink/ThatI/wantToUse',servers, {headers: headers});
  }
}  

这是app.component.ts代码:

export class AppComponent {
title = 'internship-app';
  servers=[
    {
      'token':'xyz',     //two keys, token and society, to send to api
      'society':'1'   
    }
  ];
constructor(private serverService: ServerService){}
onSave(){
    this.serverService.storeServer(this.servers)
    .subscribe(
    (response)=>console.log(response),
    (error)=>console.log(error)
    );
  }
}  

如果我通过POST方法以邮递员的x-www-form-urlencoded方法发送作为Token xyz和Society 1的键和值,我将接收到数据。 我不确定app.component.ts的servers []部分是否是将键和值发送到API的正确方法,以及我为什么在控制台中未收到任何json数据是否正确。

1 个答案:

答案 0 :(得分:0)

您正在以application/json的身份发送x-www-form-urlencoded

您可以在服务中使用以下内容:

const params = new HttpParams()
      .set('servers', servers);

return this.http.post('/login', params.toString(),
        {
           headers: new HttpHeaders()
            .set('Content-Type', 'application/x-www-form-urlencoded')
        }