Q:

Request body JSON inside JSON

I'm trying to do an iOS app using Node with express and body-parser and Swift.
In my app I encode my object that has the username and the password like this:
try? JSONEncoder().encode(requestParams)

The requestParams object is this one:
import Foundation

struct UserRequestParams: Codable {
    var username: String
    var password: String
}

Here is how I create the request.
let request = RequestBuilder.host("localhost:3000")
    .post()
    .headers(["Content-Type": "application/x-www-form-urlencoded"])
    .encoded(.body)
    .parameter(params)
    .path("auth")

And this is the request:
func execute<T: Decodable>(request: HttpRequest, responseType: T.Type) -> AnyPublisher<T, Error> {
    var urlComponents = URLComponents(string: request.stringURL)!

    if let data = request.parameter?.toJson(), request.encoded == .url {
        var queryItems = [URLQueryItem]()
        for (key,param) in data {
            queryItems.append(URLQueryItem(name: key, value: param as? String))
        }

        urlComponents.queryItems = queryItems
    }

    let url = urlComponents.url!

    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = request.method.rawValue

    if request.encoded == .body {
        urlRequest.httpBody = try? JSONEncoder().encode(request.parameter)
    }

    for header in request.headers {
        urlRequest.setValue(header.value, forHTTPHeaderField: header.key)
    }

    return URLSession.shared.dataTaskPublisher(for: urlRequest)
    .tryMap { output in
        guard let response = output.response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
            throw RepositoryError.serverError
        }
        return output.data
    }
    .receive(on: RunLoop.main)
    .decode(type: responseType.self, decoder: JSONDecoder())
    .eraseToAnyPublisher()
}`

So I think that works correctly, the problem is in the server side I am getting this request body:
body: { '{"username":"****","password":"****"}': '' }

It seems the server is already wrapping the app json into another json.

A:

"application/x-www-form-urlencoded" requires the body to be username=****&password=****
If you want JSON use "application/json"

