veritrans / veritrans.github.io

Veritrans documentation
http://veritrans.github.io
7 stars 15 forks source link

Blocked by CORS Policy #124

Closed ayungavis closed 5 years ago

ayungavis commented 5 years ago

I want to integrate SNAP to my React App but when I fetch the API I always get blocked by CORS Policy. This is of my code:

fetch('https://app.sandbox.midtrans.com/snap/v1/transactions', { method: "post", headers: new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('username:password'), 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept, Authorization', 'Access-Control-Allow-Credentials': true, }), body: JSON.stringify({ "transaction_details": { "order_id": "ORDER-102-{{$timestamp}}", "gross_amount": price }, "credit_card": { "secure": true }, "custom_field1": { "userId": uid }, "custom_field2": this.state.purchaseDescription, }) })

And this is the response:

Access to fetch at 'https://app.sandbox.midtrans.com/snap/v1/transactions' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried using HTTPS and HTTP, it still blocked. I tried build my React and it still blocked. Any solution about this?

rizdaprasetya commented 5 years ago

Hi @ayungavis for now that is expected you will get CORS issue when calling /transactions endpoint from frontend (at least until our Snap API team decided to allow CORS). Please send the API request securely from backend.

Because for security purpose, you should not call API which require Server Key authorization from Frontend. You are risking to expose your Server Key to public (which should be kept secret). Your Server Key on frontend code are easily accessible from client side. Server Key should be used from backend. You should send the frontend HTTP request to your backend first, which your backend should securely add the Authorization header, then send the request to the API.