Request JSON (http post) with Angular 2+

Asked

Viewed 1,265 times

4

I am trying to consume an api in the sandbox of braspag and am getting an error message: Xmlhttprequest cannot load https://apisandbox.braspag.com.br/v2/sales/. Response to preflight request doesn’t pass access control check: No '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 gives the following error message: Xmlhttprequest cannot load (apibraspag). Response for preflight has invalid HTTP status code 404. However, through Html/jQuery, the request is successfully performed. 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() {
}

}

4 answers

1

It is necessary to ensure that the server you are integrating has CORS support.

Another important point is to check security aspects to ensure that they do not have access to your Merchantid and Merchantkey and analyze if it is not better to keep this information on the server side.

0

Type these following codes into the server file that needs to be accessed, if you have access, if you don’t, send it along with the http request at the angle.

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

0

The payment API does not support CORS, so this will not work and it is not advisable that you leave your Secret on the client side because it will be easy to steal it and use it to cancel transactions or test stolen cards.

0

I tried to simulate your problem but could not, the code below worked perfectly (tested in Stackblitz):

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  constructor(private http: HttpClient) { }

  ngOnInit() {
    const url = 'https://apisandbox.braspag.com.br/v2/sales/';
    const data = {
      "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"
        }
      }
    };

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

    this.http.post(url, data, { headers })
      .subscribe(response => {
        console.log('Finalizado', response);
      });
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.