javascriptnode.jscoinbase-api

Cross-Origin Request Blocked using NodeJS/Coinbase API


I'm trying to get Coinbase to work using NodeJS

I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/create-payment. (Reason: CORS request did not succeed). Status code: (null).

I've tried downloading one of those Corse plugins that should allow it but I just can't get it to work.

Javascript code:

<script> const button = document.getElementById('order');

button.addEventListener('click', event => { const form = document.getElementById('payment-form');

event.preventDefault(); // Prevent the form from submitting to the server 
form.submit(); 
const price = "<?php echo $price; ?>"; 
const amount = document.getElementById('quantitymills').value;
const total_price = document.getElementById('inputd').value; 
const fname = document.getElementById('fname').value; 
const email = document.getElementById('email').value;



fetch('http://localhost:3000/create-payment', { 
method: 'POST', 
body: JSON.stringify({ price }), 
body: JSON.stringify({ amount }), 
body: JSON.stringify({ total_price }), 
body: JSON.stringify({ name }),
body: JSON.stringify({ email }), 
headers: { 
'Content-Type': 'application/json',
 }
 }) 
.then(response => response.json())
.then(payment => { 
// Do something with the payment details
 console.log(payment);
 }) 
.catch(error => console.error(error)); });

Nodejs code:

const express = require('express'); 
const axios = require('axios');
const bodyParser = require('body-parser');
const mysql = require('mysql2'); 
const app = express();

// Parse application/x-www-form-urlencoded requests app.use(bodyParser.urlencoded({ extended: false }));

// Connect to the database 
const db = mysql.createConnection({ 
 host: 'localhost',
 user: 'root',
 password: '',
 database: 'coinbase' });

// Create a payment

app.post('http://localhost:3000/create-payment', async (req, res) => { try { 
// Make an API request to create the payment 
const response = await axios.post( 
'https://api.commerce.coinbase.com/charges',
{ 
name: 'Product one', 
description: 'Product one',
local_price: { 
amount: req.body.total_price,
currency: 'USD' }, 
metadata: {}, 
pricing_type: 'fixed_price',
redirect_url: 'http://localhost/index.php' 
},
{ 
headers: 
{ 'X-CC-Api-Key': 'myapikey' } }

);

// Store the payment URL in the database
const payment = {
  url: response.data.hosted_url,
  amount: req.body.total_price,
  currency: 'USD',
  status: 'pending'
};
db.query('INSERT INTO payments SET ?', payment, (error, result) => {
  if (error) throw error;
  res.send(payment);
});

} catch (error) { console.error(error); } });

app.listen(3000, () => { console.log('Server listening on port 3000'); });

It might be something else wrong in my code, I am still new to coding and could have messed up in another area not quite sure.

Any help would be greatly appreciated!

Downloading cors plugin tried 127.0.0.1 instead of localhost tried switching ports


Solution

  • Try it like this:

    npm install --save cors
    
    

    Then inside your code put

    const cors = require('cors');
    

    at the begining and this before the row with app.listen(3000....)

    app.use(cors({
        origin: '*'
    }));
    

    This will allow request from all domains to your backend.

    To authorize only your domain (your browser requests) substitute the "star" after origin with the domain (even localhost:port) where your frontend is running.

    Hint: you should create environments variable for the domain names. So if you deploy it to a production site you can dynamically substitute them.