【发布时间】:2018-07-09 22:53:58
【问题描述】:
我在使用 PayPal-node-SDK npm 模块时遇到了真正的困难。它无法将我重定向到贝宝页面和错误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. 我阅读了有关此问题的世界,但找不到解决方法。所以我在 FE 部分使用 webpack 开发服务器的反应,并且我有 node.js/express api,它可以连接到 paypal sdk。在我的代码中,您可以看到“Access-Control-Allow-Origin”是允许的,但我仍然有 CORS 错误。这是我对 webpack 开发服务器的配置:
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);
这是我对 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));
}
}
我尝试了一切,但没有运气,所以每一个建议都会受到赞赏。有什么想法可以解决这个 CORS 问题吗?谢谢各位!
【问题讨论】:
-
Access-Control-Allow-Origin设置在响应 developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… -
changeOrigin: true是做什么的?