我的java脚本帖子请求给出了这个错误" No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。"
JavaScript(客户端)邮政编码
function doapost(exam){
$.ajax({
type: "POST",
url: "http://localhost:8080/pexam",
data: exam,
dataType: "json",
success:function(e){alert("worked")}, // The function to call on success
error: function(e){alert("never worked")},
})
}
Python(网络服务)邮政编码
class postexamhandeler(webapp2.RequestHandler):
def post(self):
owner = self.request.get('owner')
name = self.request.get('ename')
date = self.request.get('edate')
leangth = self.request.get('eleangth')
pencil = self.request.get('epencil')
pen = self.request.get('epen')
calculator = self.request.get('ecalculator')
ruller = self.request.get('eruller')
type = self.request.get('etype')
self.response.headers["Content-Type"] = "application/json"
self.response.headers['charset'] = "utf-8"
if len(name) > 0 and len(type) > 0:
self.response.out.write('{ "response": "OK"}')
else:
self.response.out.write('{ "response": "ERROR"}')
exm = makeexam(id= owner)
exm.ename = name
exm.edate = date
exm.eleangth = leangth
exm.epencil = pencil
exm.epen = pen
exm.ecalculator = calculator
exm.eruller = ruller
exm.etype = type
exm.put()
self.response.out.write('{ "response": "OK"}')
答案 0 :(得分:1)
您需要允许来自服务器的跨源请求。在PHP中,这可以解决问题
header('Access-Control-Allow-Origin: *');
通过查看你的python代码,我认为这应该有帮助(..我想)
class postexamhandeler(webapp2.RequestHandler):
def post(self):
owner = self.request.get('owner')
name = self.request.get('ename')
date = self.request.get('edate')
leangth = self.request.get('eleangth')
pencil = self.request.get('epencil')
pen = self.request.get('epen')
calculator = self.request.get('ecalculator')
ruller = self.request.get('eruller')
type = self.request.get('etype')
self.response.headers["Content-Type"] = "application/json"
self.response.headers["Access-Control-Allow-Origin"] = "*"
self.response.headers['charset'] = "utf-8"
if len(name) > 0 and len(type) > 0:
self.response.out.write('{ "response": "OK"}')
else:
self.response.out.write('{ "response": "ERROR"}')
exm = makeexam(id= owner)
exm.ename = name
exm.edate = date
exm.eleangth = leangth
exm.epencil = pencil
exm.epen = pen
exm.ecalculator = calculator
exm.eruller = ruller
exm.etype = type
exm.put()
self.response.out.write('{ "response": "OK"}')
这应该添加cors响应头
self.response.headers["Access-Control-Allow-Origin"] = "*"
答案 1 :(得分:0)
使用withCredentials
选项进行跨域请求
$.ajax({
url: "http://localhost:8080/pexam",
type: "POST",
dataType: "json",
xhrFields: {
withCredentials: true
}
}.done(function() {
// your code here
});
但服务器还必须通过将Access-Control-Allow-Credentials响应标头设置为“true”来启用凭据
Access-Control-Allow-Credentials: true
还有一个必需的标题
Access-Control-Allow-Origin: http://yourdomain.com
有关CORS(跨域资源共享)
的更多信息