我正在尝试为我的网站使用API。我正在尝试使用JSON数据发送POST请求。但是,当我尝试发送请求时,出现错误代码。我已经尝试过发送带有curl的请求,并且没有任何问题。
Access to XMLHttpRequest at 'https://mpc.getswish.net/qrg-swish/api/v1/prefilled' from origin 'http://192.168.0.90' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
卷曲命令
curl --data '{"format":"svg","size":300,"message":{"value":"test","editable":true},"amount":{"value":100,"editable":false},"transparent":true}' --header "Content-Type: application/json" --output output.png --request POST https://mpc.getswish.net/qrg-swish/api/v1/prefilled
我已经在apache配置中启用了Access-Control-Allow-Origin。
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName web
ServerAlias web
DocumentRoot /var/www/web
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Header always set Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always set Access-Control-Allow-Methods "GET,POST,PUT,OPTIONS"
</VirtualHost>
这是我的jQuery代码
$.ajax({
type: 'POST',
url: 'https://mpc.getswish.net/qrg-swish/api/v1/prefilled',
data: '{"format":"svg","size":300,"message":{"value":"test","editable":true},"amount":{"value":100,"editable":false},"transparent":true}',
headers: { 'Access-Control-Allow-Origin': '*' },
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
谢谢!
答案 0 :(得分:2)
如果您使用的是强制执行CORS的API,则可能意味着他们根本不希望您从Web浏览器中调用它。您需要做的是制作自己的后端,前端将与之对话。因此,您的AJAX调用需要转到您自己的后端,该后端调用API,然后将结果发送回去。后端可以调用没有CORS限制的API。只有网络浏览器会强制执行CORS的安全措施。