[英]XHR cannot load <URL>. No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm trying to execute a cross-domain AJAX request using JQuery. 我正在尝试使用JQuery执行跨域AJAX请求。 The server is executing a CGI file scripted in Python. 服务器正在执行使用Python编写脚本的CGI文件。 I've tried adding CORS support to the server but it doesn't appear to be working, saying: 我尝试将CORS支持添加到服务器,但是它似乎不起作用,说:
XMLHttpRequest cannot load http://<URL>.cgi. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <Other-URL> is therefore not allowed access.
The JQuery AJAX request is: JQuery AJAX请求是:
$.ajax({
type: "POST",
url: "http://<URL>.cgi",
})
.done(function(msg) {
alert(msg);
});
and the server script is: 服务器脚本是:
import os
import cgi
import cgitb; cgitb.enable()
import sys
import mysql.connector
from mysql.connector import errorcode
form = cgi.FieldStorage()
Username = form.getvalue('username')
Email = form.getvalue('email')
Password = form.getvalue('password')
print ("Content-Type: text/html")
print ("Access-Control-Allow-Origin: *")
print("<\h2>Welcome, your credentials are as follows Username: %s Email: %s Password: %s </h2>" % (Username, Email, Password))
print ("""
<html>
<head>
</head>
<body>
""")
try:
cnx = mysql.connector.connect(user='xxxxxx', password='xxxxxxx', host='127.0.0.1', database='xxxxxxx')
cursor = cnx.cursor()
#cursor.execute("INSERT INTO `user_information` (`User_ID`, `Email`, `Username`, `Password`) VALUES (NULL, %s, %s, %s)", (Email, Username, Password))
cursor.execute("SELECT * FROM `user_information` LIMIT 0 , 30")
data = cursor.fetchall()
print(data)
cnx.commit()
cursor.close()
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
print ("""
</body>
</html>
""")
Try placing print "Access-Control-Allow-Origin: *
at the top of your script instead of in the output. This finally solved it for me and didn't interfere with the script execution. 尝试将print "Access-Control-Allow-Origin: *
放在脚本的顶部而不是输出的顶部。这最终为我解决了该问题,并且不干扰脚本的执行。
My code: 我的代码:
#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-
print "Access-Control-Allow-Origin: *"
import os
import cgi
etc...
Of course, you will probably want to whitelist a specific set of domains, instead of allowing all with *. 当然,您可能希望将一组特定的域列入白名单,而不是使用*来全部包含。
Your print commands are not creating a valid HTTP header . 您的打印命令没有创建有效的HTTP标头 。 Instead of placing just placing 而不是仅仅放置
print ("Access-Control-Allow-Origin: *")
there you need to create the required CR-LF line endings and the two consecutive CR-LF to end the header. 在那里,您需要创建所需的CR-LF行尾,并创建两个连续的CR-LF以结束标题。 Also beware the automatic linefeed of the print command. 还要注意打印命令的自动换行。 This should work: 这应该工作:
print ("Content-Type: text/html\r\n"),
print ("Access-Control-Allow-Origin: *\r\n\r\n"),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.