首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS Swift 3贴子

iOS Swift 3贴子
EN

Stack Overflow用户
提问于 2017-05-27 10:41:12
回答 1查看 82关注 0票数 0

我在iOS应用程序中使用以下Swift 3代码试图更新后端MySQL数据库:

代码语言:javascript
复制
    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报告时,会得到以下错误:

代码语言:javascript
复制
MultiValueDictKeyError at /updateAPNS/
        "'devicetoken'

更令人困惑的是,反馈表明:

代码语言:javascript
复制
POST: No POST data

iOS不应该像上面代码中第3行所描述的那样张贴devicetoken变量吗?如果不是,如何在我的视图中访问devicetoken变量?

如果有帮助,我的Django视图如下:

代码语言:javascript
复制
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")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-27 17:10:58

在终端上使用curl测试一个post请求之后,我得到了:

代码语言:javascript
复制
  <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 &#39;Referer header&#39; 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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44215855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档