Whenever my frontend (React) runs at localhost:3000 and my backend (express) runs locally on localhost:8282, I get a 503 error and am able to see expected results. My fronten has been deployed at netlify and backend in heroku. I run into cors error and some other weird error that I am unable to solve. Here are the code snippets:
getting the following errors:
Access to fetch at 'https://projectname.herokuapp.com/payment' from
origin 'https://projectnamee.netlify.app' has been blocked by CORS policy: 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.
POST https://projectname.herokuapp.com/payment net::ERR_FAILED 503
fetch call in frontend:
const backend_api = process.env.NODE_ENV == 'production' ? 'https://projectname.herokuapp.com/payment' : 'http://localhost:8282/payment';
const purchase = token => {
let product = purchaseProduct
const body = {
token,
product
}
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "*"
}
return fetch(backend_api, {
method: "POST",
headers,
body: JSON.stringify(body)
}).then(response => {
console.log("Response ", response)
const {status} = response;
console.log("STATUS ", status)
})
.catch(error => console.log(error))
}
backend index.js:
require('dotenv').config();
const cors = require("cors")
const express = require("express")
const stripe = require("stripe")(process.env.STRIPE_SEC_KEY)
const { v4: uuidv4 } = require('uuid');
const app = express();
// middleware
app.use(express.json())
// I tried a lot of variations of this, none worked
app.use(cors({
origin: '*'
}))
// routes
app.get("/", (req, res) => {
res.send("Works here")
})
app.post("/payment", (req, res) => {
const {product, token} = req.body;
console.log("Product", product)
console.log("price", product.price)
console.log("email", token.email)
const idempotencyKey = uuidv4()
return stripe.customers.create({
email: token.email,
source: token.id
}).then(customer => {
stripe.charges.create({
amount: product.price * 100,
currency: 'usd',
customer: customer.id,
receipt_email: token.email,
description: `Purchase of ${product.name}`,
shipping: {
name: token.card.name,
address: {
country: token.card.address_country
}
}
}, {idempotencyKey})
}).then(result => res.status(200).json(result))
.catch(err => console.log(err))
})
// listen
const port = process.env.PORT || 8282
app.listen(port, () => console.log(`Listening on port ${port}`))