我正在尝试使用NodeJS让Coinbase工作
出现以下错误:
跨来源请求被阻止:同源策略不允许读取位于http://localhost:3000/create-payment的远程资源。(原因:CORS请求未成功)。状态代码:(无效)。
我试过下载那些应该允许它的Corse插件之一,但我就是不能让它工作。
Javascript代码:
<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)); });
节点代码:
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'); });
这可能是我的代码中的其他错误,我仍然是新的编码,可能在另一个领域搞砸了不太确定。
任何帮助将不胜感激!
Downloading cors plugin tried 127.0.0.1 instead of localhost tried switching ports
1条答案
按热度按时间oprakyz71#
试着这样做:
然后在你的代码里
在开始和这之前的行与app. listen(3000 ....)
这将允许从所有域到您的后端的请求。
要仅授权您的域(您的浏览器请求),请将源后的"星号"替换为前端运行的域(甚至是localhost:port)。
提示:你应该为域名创建环境变量。所以如果你把它部署到一个生产站点,你可以动态地替换它们。