I am trying to send a .post request from an iOS app that I have developed to a Node (v19.0.1) server that I am running. It works great, except for when including non-ISO-8859-1 characters. This is very frustrating, because when using the default iPhone keyboard, the RIGHT SINGLE QUOTATION MARK is what is actually printed when trying to use apostrophe, and is one of these problem characters. The request also fails when using double quotes, new line, or emojis (also all of these: ” “ „ ’ ‘ … – — • ₩ € ₽).
What I am wondering is if there is any way to send a request with headers that contain any of these characters. Currently, here is the Swift function I am using to send the request:
import Foundation
import Alamofire
func updateNote(date: String, title: String, note: String, id: String) {
let headers: HTTPHeaders = [
"title" : title,
"date" : date,
"note" : note,
"id" : id
]
AF.request("http://\(networkIP):8081/update", method: .post, encoding: URLEncoding.httpBody, headers: (headers))
.resume()
}
I tried making the same request with these characters in Postman and was also unable to send the request.
I understand that it is unusual to send a request with this type of data in the headers instead of in the body; I followed a tutorial I found that did it like this, and I'm wondering if there is a way to fix this issue without rewriting the backend. I'm a new programmer who is less confident with JavaScript development and would like to stay close to what the tutorial showed me.
I added the percentEncoding
(like @burnsi recommended) and that allowed me to send the request. I used .addingPercentEncoding(withAllowedCharacters: )
. The new function looked like this:
func updateNote(date: String, title: String, note: String, id: String) {
let escapedNote = note.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
let escapedTitle = title.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
let headers: HTTPHeaders = [
"title" : escapedTitle!,
"date" : date,
"note" : escapedNote!,
"id" : id
]
AF.request("http://\(networkIP):8081/update", method: .post, encoding: URLEncoding.httpBody, headers: (headers))
.resume()
}
with customAllowedSet
defined as
let customAllowedSet = NSCharacterSet(charactersIn:"\"”“„’‘…–—•₩€₽%<>\\^`{|}\n").inverted
I then only needed to decode the data on the backend in the JavaScript program using decodeURI
. Easy fix.