I'm sending my package with the following code:
func post() {
let server = "serverURLHere"
guard let url = URL(string: server) else { return }
// background task to make request with URLSession
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
guard let data = try? JSONEncoder().encode("testPackage") else { return }
// I also tried defining a variable as a string and then using .data(using: String.Encoding.utf8) on it but that didn't help at all.
urlRequest.httpBody = data
let task = URLSession.shared.dataTask(with: urlRequest) {
(data, response, error) in
if let error = error {
print(error)
return
}
guard let data = data else {return}
guard let dataString = String(data: data, encoding: String.Encoding.utf8) else {return}
// update the UI if all went OK
DispatchQueue.main.async {
print("the data we got back was \(dataString)")
}
}
// start the task
task.resume()
}
On the server side, it looks like:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const port = process.env.PORT || 5000;
const util = require('util')
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'));
http.on('request', (request, response) => {
console.log("the method request was " + request.method)
if (request.method == "GET") {
console.log("GET")
} else if (request.method == "POST") {
console.log("POST")
console.log("request: " + request)
console.log("request.body: " + request.body)
}
request.on('error', (err) => {
// This prints the error message and stack trace to `stderr`.
console.error("the error was " + err);
});
// console.log("got a request from the swifty server")
});
http.listen(port, () => console.log('listening on port ' + port));
request and request.body are both objects, but I thought request.body would contain a JSON object with the data I encoded on the client side...yet when I try to parse it, there's a big error that causes the server to crash (I think because it's empty). Not sure what to do...thanks for any help in advance!
This is the error that appears when I uncomment the console.log(JSON.parse(request.body)) line of code:
https://i.stack.imgur.com/pOIHq.jpg
When I run console.log the util.inspect on the request.body, I get the '{}':