Request JSON (http post) with Angular 2+

3

I am trying to consume an api in the braspag sandbox and am getting an error message: XMLHttpRequest can not load link . Response to preflight request does not pass access control check: In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost: 4200' is therefore not allowed access. The response had HTTP status code 404. Disabling CORS I get the following error message: XMLHttpRequest can not load (apibraspag). Response for preflight has invalid HTTP status code 404. However, through Html / jQuery, the request is successful. My code:

import { Component, OnInit } from '@angular/core';
import { Http, Headers } from '@angular/http';
@Component({
selector: 'app-app-pagamento',
templateUrl: './app-pagamento.component.html',
styleUrls: ['./app-pagamento.component.css']
})
export class AppPagamentoComponent implements OnInit {

http: Http;
constructor(http: Http) {
 this.http = http;
}

efetuarCompra() {
  let req = {
    "MerchantOrderId": "2014111703",
    "Customer": {
      "Name": "Comprador Teste"
    },
    "Payment": {
      "Type": "CreditCard",
      "Amount": 15700,
      "Provider": "Simulado",
      "Installments": 1,
      "CreditCard": {
      "CardNumber": "1234123412341231",
      "Holder": "Teste Holder",
      "ExpirationDate": "12/2021",
      "SecurityCode": "123",
      "Brand": "Visa"
      }
    }
  }

let hd = new Headers({
  'Content-Type': 'application/json',
  'MerchantId': '6d086058-35e5-4530-92b0-b2c8cd9c77ec',
  'MerchantKey': 'ILIPGAYWVALZWEKNNTHMDJZWRPISPIDYLGSWSXIH',
  'RequestId': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
});



this.http.post('https://apisandbox.braspag.com.br/v2/sales/', 
JSON.stringify(req), {headers: hd} )
   .subscribe(() => {
    console.log('Payment Sucess')
   }, erro => console.log(erro));

}

ngOnInit() {
}

}
    
asked by anonymous 02.05.2017 / 21:48

2 answers

0

Ensure that the server you are integrating on has CORS support.

Another important point is to check security aspects to ensure that you do not have access to your MerchantId and your MerchantKey and to analyze whether it is not best to keep this information on the server side.

    
12.05.2018 / 20:29
0

Type these following codes into the server file that needs to be accessed, if you have access, if you do not, send it along with the non-angled http request.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    
23.12.2018 / 21:13