我正在尝试使用NodeJS让Coinbase工作
我得到以下错误:
跨域请求阻塞:同源策略不允许读取远程资源http://localhost:3000/create-payment。(原因:CORS请求未成功)。状态码:(null).
我试着下载了一个应该允许它的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)); });
Nodejs代码:
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'); });
这可能是我的代码中的其他错误,我仍然是编码的新手,可能在其他领域搞砸了,不太确定。
任何帮助都将非常感激!
下载cors插件尝试用127.0.0.1代替localhost尝试切换端口
试一下:
npm install --save cors
然后在代码中放入
const cors = require('cors');
在开头,这之前的行与app.listen(3000....)
app.use(cors({
origin: '*'
}));
这将允许来自所有域的请求到您的后端。
若要仅授权您的域名(您的浏览器请求),请替换"在您的前端运行的域(甚至localhost:port)之后。
提示:您应该为域名创建环境变量。因此,如果您将其部署到生产站点,您可以动态地替换它们。