我与PayPal-node-SDK npm模块真的很挣扎。它无法将我重定向到paypal页面而错误Failed to load https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=******: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
而且我在这个世界上读到了这个问题,但是我找不到它的修复方法。所以我正在使用webpack dev服务器对FE部分的反应,我有node.js / express api,这使我连接到paypal sdk。在我的代码中,您可以看到" Access-Control-Allow-Origin"是允许的,但我仍然有CORS错误。这是我对webpack dev服务器的配置:
devServer: {
contentBase: Path.join(__dirname, './dist'),
historyApiFallback: true,
port: 3000,
proxy: {
"/api/*": { target: 'http://localhost:5000', secure: false, changeOrigin: true }
},
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
}

这是我的node.js api:
const express = require('express');
const cors = require('cors')
const paypal = require('paypal-rest-sdk');
// Paypal module configuration
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': '*********',
'client_secret': '**********'
});
const app = express();
app.use(cors());
app.post('/api/paypal-payment', (req, res) => {
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/paypal/success",
"cancel_url": "http://localhost:3000/paypal/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "Some Name",
"sku": "some-sku",
"price": "1",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "1"
},
"description": "Some Description"
}]
};
// Make the payment to paypal with the parameters added above
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
console.log('error', error);
} else {
console.log(payment);
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel === 'approval_url') {
res.redirect(payment.links[i].href);
}
}
}
});
}
);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
&#13;
这是我对API的axios请求:
export const handlePayment = (months) => {
return function (dispatch) {
axios.post('/api/paypal-payment, {
headers: {
'Access-Control-Allow-Origin': '*',
}
})
.then(res => dispatch({ type: FETCH_USER, payload: res.data }))
.catch(error => console.log('error', error));
}
}
&#13;
我尝试了一切,但没有运气,所以每个建议都会受到赞赏。我有什么想法可以解决这个CORS问题?谢谢你们!
答案 0 :(得分:-1)
CORS
过于参与此处,首先axios
会拦截CORS
请求,然后服务器应该允许来源。您可以查看Network
的{{1}}模块中的哪个部分。
允许axios Developer Tools
请求
CORS
答案 1 :(得分:-2)
如果您使用的是Chrome,请尝试添加此插件here 它允许您通过在请求中的标题中添加*来绕过cors检查。
希望这有帮助!