carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
727 stars 41 forks source link

HTTP 403 when trying to post dictionary body #61

Closed Loucee closed 2 years ago

Loucee commented 2 years ago

Hi! I've recently decided to switch over from AlamoFire to this because it's much more Swift-ey, but I've run into the following issue:

Back in AlamoFire I'd send my request body with Alamofire.request("https://myserver.com", method: .post, parameters: [ "title": "foo", "body": "bar", "userId": 18" ], encoding: JSONEncoding.default)

and it worked perfectly, so I rewrote this to:

Request {
        Url("https://myserver.com")
        Method(.post)
        Body([
            "title": "foo",
            "body": "bar",
            "userId": 18
        ])
}

But this however, throws back a 403 forbidden. I can't seem to understand why this happens as it worked fine using AlamoFire, and if I change the body to use an encodable instead like so:

struct Test: Codable {
        let title: String
        let body: String
        let userId: Int
    }

    Request {
        Url("https://api.loucee.dev/register")
        Method(.post)
        Body(Test(title: "foo", body: "bar", userId: 18))
    }

Everything works fine again! But the issue with this is that I have a lot of different requests to make in my app, and I rather not have 30 or so codables laying around...

My question is, what is causing this weird behaviour? Can I resolve it somehow?

Loucee commented 2 years ago

Okay I just managed to find the solution like 20 seconds after posting this, I had to add Header.ContentType(.json) and now everything works perfectly...

carson-katri commented 2 years ago

Glad you solved it! Thanks for giving swift-request a try.