我在iOS应用程序中使用以下Swift 3代码试图更新后端MySQL数据库:
var request = URLRequest(url: URL(string: "https://str8red.com/updateAPNS")!)
request.httpMethod = "POST"
let postString = "devicetoken=gjhgjgjgkkgggkgkghgkgkhjg"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()当我运行这段代码时,iOS会像预期的那样运行,并从web服务器返回500个错误。当我检查Webserver报告时,会得到以下错误:
MultiValueDictKeyError at /updateAPNS/
"'devicetoken'更令人困惑的是,反馈表明:
POST: No POST dataiOS不应该像上面代码中第3行所描述的那样张贴devicetoken变量吗?如果不是,如何在我的视图中访问devicetoken变量?
如果有帮助,我的Django视图如下:
def updateAPNS(request, extra_context={}):
currentUser = request.user
currentUserID = currentUser.id
if not currentUserID:
return HttpResponse("APNS is NOT Updated")
else:
APNSUpdate, created = APNSDevice.objects.update_or_create(user_id=currentUserID,
defaults={"user_id": currentUserID,
"registration_id": request.POST['devicetoken']})
return HttpResponse("APNS is Updated")发布于 2017-05-27 17:10:58
在终端上使用curl测试一个post请求之后,我得到了:
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this HTTPS site requires a 'Referer header' to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>一看到这一点,我就在我的视图上添加了@csrf_exempt,一切都很完美。
任何人想了解更多关于卷发的信息,请到以下网址:
https://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request
https://stackoverflow.com/questions/44215855
复制相似问题